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

认证后无法看到服务器发送的JWT Cookie问题求助

解决MERN应用Chrome中无法显示JWT Cookie的问题

以下是针对该问题的排查和解决步骤:

  • 检查跨域配置(核心问题)
    跨域场景下Cookie的传递需要前后端同时配合配置:

    • 后端CORS必须设置credentials: true,且origin不能用通配符*,要明确指定前端地址(比如http://localhost:3000),否则浏览器会拒绝接收Cookie。
    • 前端发起请求时必须带上凭证标识:Axios需设置withCredentials: true,Fetch需设置credentials: 'include'。
    • 如果用Vite代理转发请求,vite.config.js里要添加credentials: true和changeOrigin: true:
      export default defineConfig({
        server: {
          proxy: {
            '/api': {
              target: 'http://localhost:5000', // 你的后端服务地址
              changeOrigin: true,
              credentials: true
            }
          }
        }
      })
      
  • 调整Cookie的SameSite属性
    Chrome对SameSite的限制会影响跨域Cookie的存储:

    • 如果后端设置SameSite: Strict,跨域场景下Cookie不会被保存,改成SameSite: Lax适配本地开发的跨域场景。
    • 若使用SameSite: None,必须同时开启secure: true,但本地http环境下Chrome会拒绝这类Cookie,所以生产环境再启用该组合。
      后端设置示例:
    res.cookie('jwt', token, {
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
      sameSite: 'Lax',
      secure: process.env.NODE_ENV === 'production'
    })
    
  • 检查Chrome隐私设置
    若Chrome开启了「阻止第三方Cookie」,跨域请求的Cookie会被拦截。临时关闭测试:设置→隐私和安全→Cookie及其他网站数据→取消勾选「阻止第三方Cookie」。

  • 统一域名/端口标识
    确保前端请求的后端地址和Cookie的domain完全匹配:比如后端设置domain为localhost,前端就不要用127.0.0.1发起请求,反之亦然,否则Chrome会判定为不同域名,拒绝存储Cookie。

  • 清除Vite开发缓存
    Vite的缓存可能导致请求配置异常,删除项目根目录下的node_modules/.vite文件夹,或者执行npm run dev --force强制重启开发服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:38:28