You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

客户端请求API时req.user为undefined的问题排查求助

问题解决:Next.js axios请求无法获取会话用户信息

问题现象

直接在浏览器访问http://localhost:5000/api/isLoggedIn可正常返回req.user数据,但通过Next.js客户端使用axios发送GET请求时,后端返回的req.user为undefined。

核心原因

跨域请求时,浏览器默认不会携带会话Cookie,同时后端CORS配置未允许接收跨域凭证,导致会话无法在客户端与后端之间传递。

解决步骤

1. 修正后端CORS配置

在cors中间件中明确允许前端域名并开启凭证支持:

app.use(cors({
  origin: "http://localhost:3000", // 指定允许的前端域名
  credentials: true // 允许跨域请求携带凭证(Cookie)
}))

2. 优化Session的Cookie配置

调整Cookie的sameSite属性,确保跨域场景下能正常传递:

app.use(session({ 
  secret: process.env.SECRET, 
  resave: false, // 避免不必要的会话重复存储
  saveUninitialized: false, // 不存储未初始化的会话,提升安全性
  cookie: { 
    httpOnly: true, 
    secure: false, // 本地HTTP环境设为false,HTTPS环境需改为true
    sameSite: "lax", // 允许跨域请求携带Cookie
    expires: Date.now() + 1000 * 60 * 60 * 24 * 7, 
    maxAge: 1000 * 60 * 60 * 24 * 7 
  } 
}))

3. 客户端请求开启凭证携带

在axios请求中添加withCredentials: true选项,确保请求携带会话Cookie:

axios.get("http://localhost:5000/api/isLoggedIn", {
  withCredentials: true // 启用凭证携带
}).then((res) => {
  console.log(res.data)
}).catch((err) => {
  console.log(err)
})

额外说明

  • resave和saveUninitialized设为false是会话配置的最佳实践,可减少无效存储。
  • 若后续部署到HTTPS环境,需将cookie.secure设为true,同时sameSite改为"none"。

内容的提问来源于stack exchange,提问作者Yousef Alkhatib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 19:15:32