【发布时间】:2018-01-05 22:51:07
【问题描述】:
我正在使用 React 并使用 fetch 向服务器发送请求:
fetch("http://localhost:8001/api/login", {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'username=' + this.state.username + '&password=' + this.state.password
})
.then(function (response) {
console.log('Request succeeded with JSON response', data);
console.log(data.headers.toString())
})
.catch(function (error) {
console.log('Request failed', error);
});
This is chrome inspect, it shows that I get JWT token from server 我的问题是如何在我的代码中访问它?我实际上需要将它保存到一个变量中,真的没有办法做
data.headers.jwt
如果这没有意义,我很抱歉,如果您需要,我可以澄清一下。
【问题讨论】:
-
我搜索了一些,我认为这可能与这篇文章有关:stackoverflow.com/a/44816592/8608962
-
是的,服务器需要发送适当的
access-control-expose-headers来公开它们。注意:你说Request succeeded with JSON response的地方不是 JSON 响应,它是Response 对象 -
我将 header('access-control-expose-headers'); 添加到服务器文件的开头。我将如何访问 ReactJS 中的标头?
-
好吧,您需要指定要公开哪些标头 - 然后,使用
data.headers.get('jwt')访问jwt标头 -
老实说,除非有充分的理由不这样做,否则我会将
jwt放在响应正文中,而不是响应标头中 - 但是,因为您发布的代码永远不会访问响应正文,很难说将 jwt 添加到响应正文是否适合您的情况
标签: javascript reactjs http-headers fetch