Javascript 获取响应中未显示标题

Javascript 获取响应中未显示标题,javascript,node.js,fetch,Javascript,Node.js,Fetch,我可以在Chrome开发工具中看到标题“x-auth-token”。 但是,标头没有显示在我的获取响应中。 请协助,以便我可以使用标题数据 我使用NodeJS作为后端API,使用ReactJS作为前端。 这些是我的档案 NodeJS中间件-cors.js module.exports = function enableCorsSupport(app) { app.use(function(req, res, next) { res.header("Access-Control-Al

我可以在Chrome开发工具中看到标题“x-auth-token”。

但是,标头没有显示在我的获取响应中。 请协助,以便我可以使用标题数据

我使用NodeJS作为后端API,使用ReactJS作为前端。 这些是我的档案

NodeJS中间件-cors.js

module.exports = function enableCorsSupport(app) {
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type, x-auth-token");
    res.header("Access-Control-Expose-Headers", "x-auth-token");
    next();
  })
}
NodeJS路由-users.js

router.post('/login', async (req, res) => {

  // NOTE: code left out so post would be smaller

  const token = user.generateAuthToken();
  res.header('x-auth-token', token).send(_.pick(user, ['_id', 'firstName', 'email', 'isAdmin']));
})
ReactJS-我的获取请求

fetch('http://localhost:4000/api/users/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: this.props.email,
      password: this.props.password
    })
  })
  .then(res => {
    console.log('res.headers', res.headers)
    return res.json()
  })
  .then(data => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err)
  })
}
这是在我的Chrome控制台中,从console.log进入我的成功获取请求。标头响应中的标头为空。请告知。仅供参考,这是用户测试数据。

对象不是空的。它只是不是一个常规对象,所以它的实例上没有将其内容作为属性。因此,您不会在console.log视图中看到标题/值

要获取特定标头的值,需要使用以下方法

您还可以使用for…循环浏览它。。。的

for(const header of response.headers){
   console.log(header);
}
演示

fetch('https://cors-anywhere.herokuapp.com')
。然后(res=>{
for(res.headers的const header){
log(`Name:${header[0]},Value:${header[1]}`);
}

});使用Node.js我使用exposedHeaders找到了这个解决方案:

const cors=require('cors');
const express=require('express');
// ..........
var-app=express();
应用程序使用(cors)({
ExposedHeader:['x-auth-token'],

}));
公开
x-auth-token
头的另一种方法是

  res
    .header("x-auth-token", token)
    .header("access-control-expose-headers", "x-auth-token")
    .json(data);

解决了我的问题
  res
    .header("x-auth-token", token)
    .header("access-control-expose-headers", "x-auth-token")
    .json(data);