如何在响应中发送 headers nodejs

how to send headers in response nodejs

我正在尝试发送响应值中的 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!'))

问题是当我尝试在 $httpfetch 内部调用时 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 object 是一个可迭代对象,您可以使用 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}`);
    }
})