node.js - 刷新页面后如何让用户保持登录状态?
问题描述
我正在使用 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 的新手,所以如果有人可以帮助我,我会很高兴。
解决方案
可用选项之一是提供额外的授权端点。
- 用户在进入页面后发送请求,
/user
例如/auth
- 您在服务器上读取 cookie 并返回已解码(来自 cookie)的用户数据对象
- 根据响应 - 您要么登录用户要么不登录(如果您没有发现 cookie 数据或它是伪造的)
推荐阅读
- powershell - PowerShell 在 Get-ComputerInfo 的行输出开头添加破折号
- node.js - 没有为 internal-slot@^1.0.3 找到匹配的版本
- mysql - SELECT INTO OUTFILE 仅在 csv 中给出列名
- r - 如何解决这个问题,在添加 stat_pvalue_manual 后,我在条形图上显示的数字将从分组变为总数?
- plot - Matlab plot 从命令窗口而不是从函数内部生成图形
- powershell - 你如何调用rest方法powershell来获取访问令牌
- pytorch - PyTorch 的 torch.autograd.grad 中 grad_outputs 的含义
- javascript - CSS:使属性忽略过渡时间而不使用 jQuery
- flutter - VS Code - 屏幕中间的一行
- javascript - 如何获取 JSON 对象并放入 CSS