ReactJS- 将 JWT 令牌作为 http 请求的 axios 方法中的授权传递



我有一个应用程序,我们正在生成一个 JWT 令牌,并在下一个 api 调用中将该令牌传递到标头中。作为回应,我应该得到一把钥匙。我能够通过邮递员看到回应。我正在前端使用 ReactJS,并试图通过在标头中传递 JWT 令牌来实现相同的目标,同时进行 api 调用但面临一些问题。 我的代码-

getKey() {
let postData = {
vin: "5678",
id: "abc12",
};
axios({
method: "post",
url: "http://localhost:8080/generateKey",
headers: {
"Content-Type": "application/json"
},
data: postData
})
.then(function(response) {
setKey(response.data.key);
})
.catch(function(error) {
console.log(error);
getKeyError();
});
}
memberAuth() {
var self = this;
axios({
method: "GET",
url: "http://localhost:8080/authenticateMember",
headers: {
"Content-Type": "application/json",
"Authorization": localStorage.setItem()
},
data: {
"id":"xyzzy",
"password":"abc"
}
})
.then(function(response) {
//to do
}

我正在尝试将生成的令牌(有效期为 30 分钟(保存在本地存储/会话存储中,但不确定这是否是正确的方法。谁能告诉我哪里出错了。

创建axios的实例,

const agent = axios.create({
baseURL: config.api_url,
transformRequest: [transformRequest],
transformResponse: [transformResponse],
headers: { 'Content-Type': 'application/vnd.api+json' },
});

然后调用此函数动态设置标头

agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;

然后调用 axios 实例的方法进行 API 调用

agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),

最新更新