如何在响应nodejs

时间:2018-04-23 12:44:52

标签: angularjs node.js cors fetch-api

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

当我尝试在headersundefined内进行调用时,问题$http值已fetch。请让我知道我错过了什么?

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) {

});

1 个答案:

答案 0 :(得分:1)

您必须使用headers.get来检索特定标头的值。 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}`);
    }
})
  

实现Headers的对象可以直接用于for ... of   结构,而不是entries():for(var my of myHeaders)是   相当于(myHeaders.entries()的var p。)

查看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}`);
    }
})

相关问题