Headers not showing in fetch response(获取响应中未显示标头)
问题描述
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.
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]}`);
}
});
这篇关于获取响应中未显示标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取响应中未显示标头


- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01