node.js - 如何在nodejs响应中发送 header

标签 node.js angularjs 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!'))

问题是当我尝试在 $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 对象是一个可迭代对象,您可以使用 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/

相关文章:

javascript - 如何从 Node.js API 正确发送响应代码

javascript - 无法将 eval() 与 Angular 一起使用

reactjs - 使用 SWR 单击时向 API 路由发出请求时出现太多重新呈现错误

reactjs - 自定义 fetchBasequery 以进行错误处理

javascript - NodeJS : Value for shared state of module

node.js - 如何处理级联可观察值

node.js - Knex.js 无法连接到 postgres

java - 如何使用 @ControllerAdvice 在 Spring MVC 中返回 ResponseEntity 的方法中返回错误消息

javascript - 选定的表行 angular.js

javascript - 如何使用 "this"和 fetch ?