标头未显示在提取响应中 [英] Headers not showing in fetch response

查看:34
本文介绍了标头未显示在提取响应中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在Chrome DevTools中看到标题"x-auth-token".

I can see the header "x-auth-token" in Chrome DevTools.

但是,标头未显示在我的提取响应中.请协助,以便我可以使用标头数据.

However, the header is not showing up in my fetch response. Please assist so I can use header data.

我将NodeJS用作后端API,并将ReactJS用作前端.这些是我的文件.

I am using NodeJS as my backend API and ReactJS as my front-end. These are my files.

NodeJS中间件-cors.js

NodeJS middleware - 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

NodeJS route - 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-我的提取请求

ReactJS - my fetch request

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

这是我成功获取请求中console.log中的Chrome控制台中的内容.标头响应中的标头为空.请指教.仅供参考,这是用户测试数据.

This is in my Chrome console from the console.log in my successful fetch request. Headers are empty in the header response. Please advise. FYI this is user test data.

推荐答案

Header 对象不为空.它只是一个非常规对象,因此它的内容没有作为属性的内容.这样,您将不会在console.log视图中看到标题/值.

The Header object is not empty. It is just not a regular object so it doesn't have its contents as properties on its instance. As such you won't see the headers / values in a console.log view.

要获取特定标头的值,您需要使用 get() 方法

To get a particular header's value you need to use the get() method

var token = response.headers.get('x-auth-token');
console.log(token);

您也可以使用...的

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

演示

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

这篇关于标头未显示在提取响应中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆