[英]ReactJS protected route with API call
I'm trying to protect my routes in ReactJS. 我正在尝试保护我在ReactJS中的路由。 On each protected routes I want to check if the user saved in localStorage is good. 在每个受保护的路由上,我要检查在localStorage中保存的用户是否良好。
Below you can see my routes file (app.js) : 在下面,您可以看到我的路线文件(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>
);
}
}
My protectedRoute file : 我的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;
And my function isRightUser
. 我的函数是isRightUser
。 This function send a status(401)
when the data aren't valid for the user logged : 当数据对于登录的用户无效时,此函数发送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;
}
This code is not working and I don't know really why. 此代码无法正常工作,我也不知道为什么。 Maybe I need to call my function AuthService.isRightUser()
with a await
before the call and put my function async ? 也许我需要在调用之前await
我的函数AuthService.isRightUser()
并将其异步处理?
How can I update my code to check my user before accessing a protected page ? 在访问受保护的页面之前,如何更新代码以检查用户?
I had the same issue and resolved it by making my protected route a stateful class. 我遇到了同样的问题,并通过将受保护的路由设置为有状态类来解决了该问题。
Inside switch I used 我使用的内部开关
<PrivateRoute
path="/path"
component={Discover}
exact={true}
/>
And my PrivateRoute class is as following 我的PrivateRoute类如下
class PrivateRoute extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
isLoading: true,
isLoggedIn: false
};
// Your axios call here
// For success, update state like
this.setState(() => ({ isLoading: false, isLoggedIn: true }));
// For fail, update state like
this.setState(() => ({ isLoading: false, isLoggedIn: false }));
}
render() {
return this.state.isLoading ? null :
this.state.isLoggedIn ?
<Route path={this.props.path} component={this.props.component} exact={this.props.exact}/> :
<Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />
}
}
export default PrivateRoute;
When you annotate a function with async
like you did in AuthService.isRightUser()
it returns a Promise
and you are not treating the response of the method accordingly. 当您像在AuthService.isRightUser()
那样对带有async
功能的函数进行注释时,它将返回Promise
并且您不会相应地处理方法的响应。
As you suggested, you could call the method AuthService.isRightUser()
with await
and annotate the function you are passing to the render
property with async
. 如您所建议,您可以使用await
调用AuthService.isRightUser()
方法,并使用async
注释传递给render
属性的函数。
Or you could treat the response of AuthService.isRightUser()
with a .then()
and .catch()
instead of the ternary operator 或者,您可以使用AuthService.isRightUser()
.then()
和.catch()
而不是三元运算符来处理AuthService.isRightUser()
的响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.