[英]NodeJS http server response headers are blank when headers are set for a request
So I'm sending a request via ajax and I'm setting the headers there and I can log and see that the headers are indeed being set 所以我通过ajax发送请求,并在其中设置标头,我可以登录并看到标头确实已设置
$.ajax({
headers: {
Authorization: localStorage.getItem('t')
},
type: 'GET',
dataType: 'json',
url: `/updatebackground?b=${bg}`,
success: function(data) {
console.log('yay');
},
complete: function() {
console.log(this.headers)
}
});
But when I try to log the headers in node they come back as blank 但是当我尝试将标头记录在节点中时,它们以空白形式返回
http.createServer(async (req, res) => {
console.log(JSON.stringify(res._headers));
});
logs "{}"
I'm unsure as to why this happens and any help would be appreciated 日志
"{}"
我不确定为什么会发生这种情况,我们将不胜感激
Apparenly it works with req.headers.authorization Doesn't really make sense as to why it's lowercase but eh whatever. 显然,它可以与req.headers.authorization一起使用。为何它是小写的并没有任何意义。 I'll keep this here for anyone else with the same issue.
我将把这个问题留在这里给其他有同样问题的人使用。
On the server, you're trying to access the headers on the response object, not the request object. 在服务器上,您尝试访问响应对象(而不是请求对象)上的标头。 Since the client set the headers on the request the desired headers would be on the request, or
req
. 由于客户端在请求上设置标头,因此所需的标头将在请求或
req
。
If you change that server-side code to: 如果您将该服务器端代码更改为:
http.createServer(async (req, res) => {
console.log(req.headers);
});
You will see the request headers 您将看到请求标头
This is because you are logging the res headers and not the req headers. 这是因为您正在记录res标头,而不是req标头。
the proper code for logging the request headers is: 记录请求标头的正确代码是:
http.createServer(async (req, res) => {
console.log(JSON.stringify(req.headers));
});
res._headers is for setting the headers for the response that is sent by the server to client as the request's answer. res._headers用于设置服务器发送到客户端作为请求答案的响应的标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.