【发布时间】:2018-10-25 15:58:28
【问题描述】:
我正在使用反应路由器私有路由系统。我正在检查身份验证,方法是从本地存储获取 jwt 并在 axios 承诺 中对服务器进行交叉检查。
但是,私有路由似乎没有等待回调返回。 我做的认证错了吗?或者有没有办法解决这个问题?
我的 axios 承诺会检查身份验证。
const checkAuth = (cb) => {
let token = localStorage.getItem("jwtToken");
// console.log(token);
if (token) {
axios.defaults.headers.common["Authorization"] = token;
axios
.get("api/admin/auth/profile")
.then(res => {
localStorage.setItem("admin", res.data.admin);
cb(null, res.data);
})
.catch(err => {
showErr(err, cb);
});
} else {
cb("Not authenticated", null);
}
}
私人路线设置。
const PrivateRoute = ({ component: Component, ...rest, checkAuth }) =>
(
<Route {...rest} render={(props) => (
checkAuth((isAuthenticated) => (
isAuthenticated === true
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
))
)} />
)
【问题讨论】:
标签: reactjs authentication callback access-token react-router-v4