如何通过Axios&传递标头JWT令牌有反应吗 [英] How to pass Header JWT Token with Axios & React?
问题描述
我使用React,Express,MongoDB制作Web应用程序.
I make web application with React, Express, MongoDB.
而且,我想通过标头传递jwt令牌.
And, I want to pass jwt token with header.
但是,我通过了它,得到401错误(未经授权).
But, I pass it, get 401 error (Unauthorized).
在登录actions.js中:
In login actions.js :
export function login(username, password) {
return function(dispatch) {
axios
.post(`${API_URL}/auth/login`, { username, password })
.then(res => {
dispatch(loginSuccess(res.data, username));
const token = res.data.token;
axios.defaults.headers.common["Authorization"] = token;
history.push("/");
})
.catch(err => {
if (err.response.status === 401) {
dispatch(loginFailure(err));
}
});
};
}
然后,在我的post.js服务器中:
And, In my post.js in server :
getToken = function(headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(" ");
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
...
// Save Post
router.post("/", passport.authenticate("jwt", { session: false }),
function(
req,
res,
next
) {
var token = getToken(req.headers);
if (token) {
Post.create(req.body, function(err, post) {
if (err) return next(err);
res.json(post);
});
} else {
return res.status(403).send({ success: false, msg: "Unauthorized." });
}
});
我该如何解决? +登录成功
How I do fix it? + Login is success
推荐答案
首先,当您登录并将用户名和密码发送到后端时,作为响应,您会得到token_id.现在尝试将令牌存储在session_storage中并重定向到您的需求页面.现在,在您的需求页面中使用token_id并像这样存储一个变量.
First of all when you login and send username and password to backend then in response you get token_id. now try to token store in session_storage and redirect to your desire page. now you take token_id in your desire page and store one variable as like..
let user = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id;
现在您有了令牌并传递了标头,并获得了响应数据
now you have token and pass in the header and get data in response
const api = `your api here`
axios.get(api, { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
this.setState({
items: res.data, /*set response data in items array*/
isLoaded : true,
redirectToReferrer: false
})
注意:,您应该像在初始setState中那样设置空白项目数组
note : you should set blank items array in initial setState as like
this.state={
items:[],
isLoaded: false,
redirectToReferrer:false,
token:''
}
这篇关于如何通过Axios&传递标头JWT令牌有反应吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!