首页 > 解决方案 > 刷新页面后如何让用户保持登录状态?

问题描述

我正在使用 Auth 系统制作一个迷你应用程序。在后端,我使用放入 Cookie 中的 NodeJS 和 JWT 令牌并检查它并制作受保护的中间件。这一切对我来说都很好,但是在前端(React)上,当我登录时一切正常,直到我刷新页面,当我刷新它时,用户是一个空对象并且我的状态被重置。刷新页面后如何保持登录用户?

这是我的 React Reducer:

export const userLoginReducer = (state = { user: {} }, action) => {
  switch (action.type) {
    case USER_LOGIN_REQUEST:
      return { loading: true, isAuthenticated: false };
    case USER_LOGIN_SUCCESS:
      return {
        ...state,
        loading: false,
        isAuthenticated: true,
        user: action.payload,
      };
    case USER_LOGIN_FAIL:
      return { loading: false, isAuthenticated: false, error: action.payload };
    case USER_LOGOUT:
      return { loading: false, isAuthenticated: false, user: null };
    default:
      return state;
  }
};

这是我的反应动作:

const { data } = await API.post(
  '/api/v1/users/login',
  { email, password },
  config
);



 dispatch({
      type: USER_LOGIN_SUCCESS,
      payload: data,
    });
} catch (error) {
    dispatch({
      type: USER_LOGIN_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

API 是 Axios 的配置:

export default axios.create({
  baseURL: 'http://localhost:8000',
  withCredentials: true,
  credentials: 'include',
});

这是我的登录屏幕:

const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const redirect = location.search ? location.search.split('=')[1] : '/';

  const dispatch = useDispatch();

  const userLogin = useSelector(state => state.userLogin);
  const { loading, error, isAuthenticated } = userLogin;

  useEffect(() => {
    if (isAuthenticated) {
      history.push(redirect);
    }

    if (error) {
      console.log(error);
    }
  }, [isAuthenticated, history, redirect, error]);

  const submitHandler = e => {
    e.preventDefault();
    dispatch(login(email, password));
  };

我是 React 的新手,所以如果有人可以帮助我,我会很高兴。

标签: node.jsreactjsredux

解决方案


可用选项之一是提供额外的授权端点。

  1. 用户在进入页面后发送请求,/user例如/auth
  2. 您在服务器上读取 cookie 并返回已解码(来自 cookie)的用户数据对象
  3. 根据响应 - 您要么登录用户要么不登录(如果您没有发现 cookie 数据或它是伪造的)

推荐阅读