[英]When to set the headers explicitly when making HTTP request in NodeJS application
[英]NodeJS http server response headers are blank when headers are set for a request
所以我通過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)
}
});
但是當我嘗試將標頭記錄在節點中時,它們以空白形式返回
http.createServer(async (req, res) => {
console.log(JSON.stringify(res._headers));
});
日志"{}"
我不確定為什么會發生這種情況,我們將不勝感激
顯然,它可以與req.headers.authorization一起使用。為何它是小寫的並沒有任何意義。 我將把這個問題留在這里給其他有同樣問題的人使用。
在服務器上,您嘗試訪問響應對象(而不是請求對象)上的標頭。 由於客戶端在請求上設置標頭,因此所需的標頭將在請求或req
。
如果您將該服務器端代碼更改為:
http.createServer(async (req, res) => {
console.log(req.headers);
});
您將看到請求標頭
這是因為您正在記錄res標頭,而不是req標頭。
記錄請求標頭的正確代碼是:
http.createServer(async (req, res) => {
console.log(JSON.stringify(req.headers));
});
res._headers用於設置服務器發送到客戶端作為請求答案的響應的標頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.