React检查登录状态时出现401错误(Express+Passport后端)
登录后调用/check-login接口持续返回401未授权问题
注册请求完全正常,说明前后端连接无误,但React前端执行登录后,调用/check-login接口检查登录状态时持续出现401未授权错误,即使将axios.get请求放入useEffect钩子中也无法解决。用Postman发送/check-login的GET请求一切正常,但通过React应用登录时就触发401错误。
前端代码
const handleLogin = async (e) => { e.preventDefault(); try { const response = await axios.post('http://localhost:5000/login', loginForm); console.log(response.data); setLoginForm({ username: '', password: '' }) const response2 = await axios.get('http://localhost:5000/check-login', {withCredentials: true}); console.log(response2.data); setIsLoggedIn(response.data.loggedIn); } catch (err) { console.log(err); } }
后端代码
app.get('/check-login', (req, res) => { if (req.isAuthenticated()) { console.log("Is Authenticated?", req.isAuthenticated()); res.status(200).json({message: 'User is Logged in'}); } else { res.status(401).json({message: 'User is not logged in'}); } })
完整错误信息
GET http://localhost:5000/check-login 401 (Unauthorized)
handleCheckLogin
AxiosError
{ message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}, response: {data: {…}, status: 401, statusText: 'Unauthorized', headers: AxiosHeaders, config: {…}, …}, stack: "AxiosError: Request failed with status code 401" }
CORS配置
const cors = require('cors'); app.use(cors({ origin: "http://localhost:5173", methods: "GET,PUT,POST,DELETE", credentials: true, }));
排查与解决方案
- 登录请求需携带
withCredentials:当前仅/check-login请求加了该配置,但登录的POST请求也需要添加{withCredentials: true},否则跨域场景下后端设置的Session Cookie无法被前端保存,后续请求自然无法携带认证信息。修改后的登录请求:const response = await axios.post('http://localhost:5000/login', loginForm, {withCredentials: true}); - 检查后端Session配置:如果使用
express-session,需确保配置中设置了sameSite: 'none'(跨域场景必须)、secure: process.env.NODE_ENV === 'production'(本地开发时设为false,因为HTTP协议下secure=true会导致Cookie无法保存),同时domain设为localhost(本地环境)。示例配置:app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { sameSite: 'none', secure: process.env.NODE_ENV === 'production', maxAge: 24 * 60 * 60 * 1000, domain: 'localhost' } })); - 全局配置Axios的
withCredentials:可以在项目初始化时全局设置,避免每个请求重复配置:import axios from 'axios'; axios.defaults.withCredentials = true; - 确认登录接口的认证逻辑:后端登录接口需确保调用了
req.login()(Passport.js)或其他会话创建方法,成功生成并返回Session Cookie。
内容的提问来源于stack exchange,提问作者Joshua Reitz
相关产品推荐
相关产品推荐

