我尝试在响应值中发送 headers
字段,如下所示:
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
app.use('/', function(req, res){
var data = {
success: true,
message: "Login success"
};
res.setHeader('custom_header_name', 'abcde');
res.status(200).json(data);
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
问题是当我尝试在 $http
和 fetch
内部调用时,headers
值变为 undefined
。请告诉我我错过了什么?
获取
fetch('http://localhost:3000').then(function(response) {
console.log(JSON.stringify(response)); // returns a Headers{} object
})
$http
$http({
method: 'GET',
url: 'http://localhost:3000/'
}).success(function(data, status, headers, config) {
console.log('header');
console.log(JSON.stringify(headers));
}).error(function(msg, code) {
});
最佳答案
您必须使用headers.get
来检索特定 header 的值。 headers 对象是一个可迭代对象,您可以使用 for..of
打印其所有条目。
fetch('http://localhost:3000').then(function(response) {
// response.headers.custom_header_name => undefined
console.log(response.headers.get('custom_header_name')); // abcde
// for(... of response.headers.entries())
for(const [key, value] of response.headers) {
console.log(`${key}: ${value}`);
}
})
An object implementing Headers can directly be used in a for...of structure, instead of entries(): for (var p of myHeaders) is equivalent to for (var p of myHeaders.entries()).
检查the docs了解更多信息。
<小时/>工作示例
fetch('https://developer.mozilla.org/en-US/docs/Web/API/Headers').then(function(response) {
console.log(response.headers.get('Content-Type')); // Case insensitive
for(const [key, value] of response.headers) {
console.log(`${key}: ${value}`);
}
})
关于node.js - 如何在nodejs响应中发送 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981425/