san*_*der 1 javascript fetch http-headers reactjs
我正在使用 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);
});
Run Code Online (Sandbox Code Playgroud)
这是 chrome 检查,它显示我从服务器获取 JWT 令牌 我的问题是如何在我的代码中访问它?我实际上需要将它保存到一个变量中,真的没有办法
data.headers.jwt
Run Code Online (Sandbox Code Playgroud)
如果这没有意义,我很抱歉,如果您需要,我可以澄清。
这是您需要的代码。作为奖励,我添加了一些代码来向您展示如何使用响应数据。
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('My JWT:', response.headers.get('jwt'));
return response.json();
})
.then(function (data) {
// Do something with JSON data.
})
.catch(function (error) {
console.log('Request failed', error);
});
Run Code Online (Sandbox Code Playgroud)