[英]ReactJS- Pass the JWT token as Authorization in axios method for http request
我有一个应用程序,我们在其中生成一个JWT令牌并在下一个api调用中将其传递到Header中作为响应,我应该获得一个密钥,我可以通过邮递员看到响应。前端并尝试通过在进行api调用时在Header中传递JWT令牌来实现相同目的,但遇到了一些问题。 我的代码-
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分钟)保存在localStorage / SessionStorage中,但不确定这是否正确。 有人可以告诉我我要去哪里错了。
创建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)),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.