使用API​​调用的ReactJS保护的路由

时间:2019-04-10 11:39:02

标签: javascript reactjs routes async-await react-router-dom

我正在尝试保护我在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;
}

此代码无效,我也不知道为什么。 也许我需要在调用之前用AuthService.isRightUser()调用函数await并使我的函数异步?

在访问受保护的页面之前,如何更新代码以检查用户?

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,并通过将受保护的路由设置为有状态类来解决了该问题。

我使用的内部开关

<PrivateRoute 
    path="/path"
    component={Discover}
    exact={true}
/>

我的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;

答案 1 :(得分:0)

当您像在async中一样用AuthService.isRightUser()注释函数时,它将返回Promise,并且您没有相应地处理方法的响应。

如您所建议,可以用AuthService.isRightUser()调用方法await并用render注释传递给async属性的函数。

或者您可以用AuthService.isRightUser().then()而不是三元运算符来处理.catch()的响应