【发布时间】:2020-06-02 10:34:09
【问题描述】:
编辑
我已经能够使用 curl 直接联系后端,它肯定会发送尾随标头。它似乎在body之后的输出流中,所以可能我的api例程需要稍后检查它,或者它可能没有通过nginx。
第二次编辑 我使用 curl 直接访问后端我看到了尾随标头。联系前端(Nginx)我没看到
原始问题
我正在尝试制作一个节点服务器来响应来自客户端的 API 请求。
此服务器是由 nginx 代理的后端,它可能会剥离标头,但是... 这是它的反向代理配置,所以我不这么认为
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://localhost:2040;
proxy_redirect off;
proxy_buffering off;
proxy_cache off;
}
服务器正在处理这样的特定 api 请求
router.post('/api/process', async (req,res) => {
res.writeHead(200, {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'X-Accel-Buffering': 'no',
'Trailer': 'API-Status'
});
try {
response = await callApiProcessor(req.params);
res.write(JSON.stringify(response));
res.addTrailers({'API-Status': 'OK'})
catch (e) {
res.addTrailers({'API-Status': e.toString()});
}
res.end();
});
在浏览器端,我正在使用这样的 fetch api
export default function api(url, params, signal) {
const options = {
credentials: 'same-origin',
method: 'post',
headers: new Headers({
'content-type': 'application/json'
}),
body: JSON.stringify(params)
};
if (signal) options.signal = signal;
return window.fetch('/api/' + url, options).then(response => {
if (!response.ok || response.headers['API-Status'] !== 'OK') {
if (response.ok) console.warn('SERVER API Error:', response.headers['API-Status']);
window.dispatchEvent(new LogoffRequest());
//put us back to home
window.history.pushState({}, null, '/');
window.dispatchEvent(new LocationAltered());
return {};
} else {
return response.json();
}
});
}
通过在 api 模块中放置断点,我在响应中看不到任何标题。所以尽管response.ok 是真的,我仍然在我的应用程序中强制客户端注销。
查看 Chrome 的 Dev Tools Networking 选项卡,我看不到 API 状态,尽管我看到了 Trailer 标头。
【问题讨论】:
标签: node.js http-headers nginx-reverse-proxy