我试图使用njs使用nginx进行链式请求,下面的问题是我的javascript文件,我的场景是我有两个API。我想请求第一个api并得到它的响应,然后追加第一个api的响应(云是JSON属性),第二个api的头
async function chain(r) {
r.headersOut["Content-Type"] = "application/json";
var result = await r.subrequest("/validation", { method: "POST" });
var json = JSON.parse(result.responseText);
headers = json.fullName;// where to put this header and append it to second request header ?
var result1 = await r.subrequest("/persistance");
r.return(result1.status, result1.responseBody);
}
function getHeaders() {
return headers;
}
export default { chain, getHeaders };和我的nginx配置文件
js_import http.js;
js_set $headers http.getHeaders; // here am trying to get headers from variable in http.js but is it alwat null and undefended
server {
listen 80;
listen [::]:80;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location ~ ^/.*$ {
js_content http.chain;
}
location = /persistance {
proxy_set_header accountId $headers; //it is always undefined, I think it is because declared on the top of file and it is nginx directives
proxy_pass http://192.168.2.76:5001/academicyear/list;
}
location = /validation {
proxy_pass http://192.168.2.76:8088/v1/user/validation;
}
}我使用子请求和,然后使用--这是同一个问题
发布于 2022-06-28 16:35:39
这个评论可能就是答案。

nginx不支持其变量处理程序中的异步操作(它与JavaScript中的异步关键字无关)。当nginx想要某个变量(比如$x_js_log)的值时,它会找到它并调用它的处理程序(js_log)。Nginx不能阻止这里,并且想马上得到结果。r.subrequest()本质上是一个异步操作。
https://github.com/nginx/njs/issues/287#issuecomment-584247289
https://stackoverflow.com/questions/71869134
复制相似问题