在反应路由器渲染之前在服务器端获取auth的cookie

时间:2019-10-28 11:28:33

标签: node.js reactjs cookies async-await react-router-dom

我正在用nodejs进行登录。当您登录时,该应用程序在nodejs中保存了一个httponly cookie,但是当我尝试恢复它时却遇到了一些问题。 那就是我的减速器,我称之为“ getCookie()”:

export const AuthReducer: React.Reducer<AppState, Action> = (state, action) => {
        switch (action.type) {
            case 'setIsAuthenticated':
                return { User: state.User, isAuthenticated: action.payload };

            case 'setUser':
                return { User: action.payload, isAuthenticated: true };

            case 'getUser':
                getCookie();
                return { User: state.User, isAuthenticated: state.isAuthenticated };

            case 'login':
                return { User: action.payload, isAuthenticated: true };

            case 'logout':
                return { User: AuthInitialState.User, isAuthenticated: AuthInitialState.isAuthenticated };
            default:
                throw new Error()
        }

};

这里是“ getCookie()”,它调用API以获取Cookie并检查凭据:

export const getCookie = async () => {
     await axios.post('/api/getCookie')
        .then(res => {
            if(res.data.token && res.data.token !== undefined) {
                const user:User = jwtDecode(res.data.token);
                axios.post('/api/checkSign', {id: user.id, firma: user.sign})
                    .then(response => {
                        if (response.data.find) {
                            dispatch({type: 'setUser', payload: user});
                            console.log(user);
                        }else{
                            destroyCookie();
                        }
                    })
            }else{
                destroyCookie();
            }
        });
};

我以为一切正常,但是当浏览器在“ PrivateRoute”中刷新时,它找不到身份验证,而且我认为问题在于React会在设置身份验证之前渲染它。那就是我的路线代码:

const Routes = () => {
let [user] = useGlobalState('User');
let [isAuthenticated] = useGlobalState('isAuthenticated');

return (
    <MDBContainer>
        <BrowserRouter>
            <header>
                <Header/>
            </header>
                <div id="home">
                    <Switch>
                        ...
                        <PrivateRoute path="/user" user={user} auth={isAuthenticated} component={DetalleUsuario}/>
                        <Redirect to="/"/>
                    </Switch>
                </div>
            <Footer/>
        </BrowserRouter>
    </MDBContainer>
)

};

const PrivateRoute = ({component: Component, user, auth, ...rest}: PrivateRouterProps) =>{

return(
    <>
        <Route {...rest} render={(props) => (
            user && auth === true
                ? <Component {...props} />
                : <Redirect to='/login'/>
        )}/>
    </>
)

};

还有我在调度的reducer中调用'getUser'时的应用代码:

const App = () => {

useEffect(() => {

    const getAuth = async () => {
        await dispatch({type: 'getUser'});
    };

    getAuth();
}, []);

};

有人可以帮助我吗?

0 个答案:

没有答案