使用react + localstorage进行身份验证

时间:2018-05-02 21:26:19

标签: javascript reactjs authentication async-await local-storage

我编写以下代码以使用react进行身份验证但有一个问题。用户登录后,在本地存储中设置令牌并将用户重定向到仪表板,在此页面中检查来自本地存储的令牌,如果不存在,则将用户重定向到登录页面,我的问题就在这里!当进入仪表板页面时无法获取令牌,因为返回null给我但是如果刷新页面返回令牌!!

事实上,在设定之后我无法获得令牌。

我的代码是:

export const userLogin = (data) => {
    return (dispatch) => {
        return axios.post(API.USER_LOGIN,data).then((response) => {
            dispatch(loginSuccess());
            setToken(response.data.token);
            dispatch(setUserToken(response.data.token))
        }).then(() => {
            dispatch(fetchUser());
        }).catch((error) => {
            dispatch(setFormErrors({errors: error.response.data}));
        })
    }
};

export const fetchUser = () => {
    return (dispatch, getState) => {
        dispatch(authLoading(true));
        const { userToken } = getState().auth;
        return axios.post(API.CURRENT_USER, null, {
            headers: { authorization: `Bearer ${userToken}` },
        }).then((response) => {
            const { id, name, username, email } = response.data.user;
            dispatch(setCurrentUser({current_user: { id, name, username, email }}));
            dispatch(authLoading(false));
        }).catch((error) => {
            if(error.response.status) {
                dispatch(logout());
            }
        });
    };
};

export const checkToken = () => {
    return async (dispatch, getState) => {
        const token = await getToken();
        const { userToken } = getState().auth;
        if (token || userToken) {
            dispatch(loginSuccess());
            dispatch(fetchUser());
        }
    };
}

export const setToken = token => localStorage.setItem('token', token);
export const getToken = () => localStorage.getItem('token');
export const clearToken = () => localStorage.removeItem('token');

0 个答案:

没有答案