admin管理员组文章数量:1421564
I'm trying to protect my routes in ReactJS. On each protected routes I want to check if the user saved in localStorage is good.
Below you can see my routes file (app.js) :
class App extends Component {
render() {
return (
<div>
<Header />
<Switch>
<Route exact path="/" ponent={Home} />
<Route path="/login" ponent={Login} />
<Route path="/signup" ponent={SignUp} />
<Route path="/contact" ponent={Contact} />
<ProtectedRoute exac path="/user" ponent={Profile} />
<ProtectedRoute path="/user/person" ponent={SignUpPerson} />
<Route ponent={NotFound} />
</Switch>
<Footer />
</div>
);
}
}
My protectedRoute file :
const ProtectedRoute = ({ ponent: 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
. This function send a status(401)
when the data aren't valid for the user logged :
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 ?
How can I update my code to check my user before accessing a protected page ?
I'm trying to protect my routes in ReactJS. On each protected routes I want to check if the user saved in localStorage is good.
Below you can see my routes file (app.js) :
class App extends Component {
render() {
return (
<div>
<Header />
<Switch>
<Route exact path="/" ponent={Home} />
<Route path="/login" ponent={Login} />
<Route path="/signup" ponent={SignUp} />
<Route path="/contact" ponent={Contact} />
<ProtectedRoute exac path="/user" ponent={Profile} />
<ProtectedRoute path="/user/person" ponent={SignUpPerson} />
<Route ponent={NotFound} />
</Switch>
<Footer />
</div>
);
}
}
My protectedRoute file :
const ProtectedRoute = ({ ponent: 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
. This function send a status(401)
when the data aren't valid for the user logged :
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 ?
How can I update my code to check my user before accessing a protected page ?
Share Improve this question asked Apr 10, 2019 at 11:39 CracsCracs 5251 gold badge8 silver badges31 bronze badges2 Answers
Reset to default 6I had the same issue and resolved it by making my protected route a stateful class.
Inside switch I used
<PrivateRoute
path="/path"
ponent={Discover}
exact={true}
/>
And my PrivateRoute class is as following
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} ponent={this.props.ponent} 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.
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
.
Or you could treat the response of AuthService.isRightUser()
with a .then()
and .catch()
instead of the ternary operator
本文标签: javascriptReactJS protected route with API callStack Overflow
版权声明:本文标题:javascript - ReactJS protected route with API call - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745344411a2654412.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论