繁体   English   中英

如何使用提取保存JWT响应标头?

[英]How do I save JWT response header using fetch?

我正在使用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);
});

这是chrome inspect,它表明我从服务器获取了JWT令牌。我的问题是如何在代码中访问它? 我实际上需要将其保存到变量中,实际上没有办法

data.headers.jwt

很抱歉,如果这没有意义,请您澄清一下。

这是您需要的代码。 另外,我添加了一些代码来向您展示如何使用响应数据。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM