Headers not showing in fetch response

和自甴很熟 提交于 2021-02-08 12:49:07

问题


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.

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

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

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.


回答1:


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.

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

You can also loop through it using for ... of

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

Demo

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



回答2:


With Node.js I found this solution, using exposedHeaders:

const cors = require('cors');
const express = require('express');

// ..........

var app = express();
app.use(cors({
  exposedHeaders: ['x-auth-token'],
}));

And for read, it's ok:

x_auth_token = res.headers.get('x-auth-token');


来源:https://stackoverflow.com/questions/50779681/headers-not-showing-in-fetch-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!