【发布时间】:2019-08-31 20:35:26
【问题描述】:
我正在尝试在 ReactJS 中保护我的路由。 在每个受保护的路由上,我想检查保存在 localStorage 中的用户是否良好。
你可以在下面看到我的路由文件(app.js):
class App extends Component {
render() {
return (
<div>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/signup" component={SignUp} />
<Route path="/contact" component={Contact} />
<ProtectedRoute exac path="/user" component={Profile} />
<ProtectedRoute path="/user/person" component={SignUpPerson} />
<Route component={NotFound} />
</Switch>
<Footer />
</div>
);
}
}
我的 protectedRoute 文件:
const ProtectedRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
AuthService.isRightUser() ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)} />
);
export default ProtectedRoute;
还有我的函数isRightUser。当数据对登录的用户无效时,此函数会发送status(401):
async isRightUser() {
var result = true;
//get token user saved in localStorage
const userAuth = this.get();
if (userAuth) {
await axios.get('/api/users/user', {
headers: { Authorization: userAuth }
}).catch(err => {
if (!err.response.data.auth) {
//Clear localStorage
//this.clear();
}
result = false;
});
}
return result;
}
此代码不起作用,我不知道为什么。
也许我需要在调用之前用await 调用我的函数AuthService.isRightUser() 并将我的函数异步?
如何在访问受保护页面之前更新我的代码以检查我的用户?
【问题讨论】:
标签: javascript reactjs routes async-await react-router-dom