簡體   English   中英

使用API​​調用的ReactJS保護的路由

[英]ReactJS protected route with API call

我正在嘗試保護我在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()並將其異步處理?

在訪問受保護的頁面之前,如何更新代碼以檢查用戶?

我遇到了同樣的問題,並通過將受保護的路由設置為有狀態類來解決了該問題。

我使用的內部開關

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

當您像在AuthService.isRightUser()那樣對帶有async功能的函數進行注釋時,它將返回Promise並且您不會相應地處理方法的響應。

如您所建議,您可以使用await調用AuthService.isRightUser()方法,並使用async注釋傳遞給render屬性的函數。

或者,您可以使用AuthService.isRightUser() .then().catch()而不是三元運算符來處理AuthService.isRightUser()的響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM