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

Vite创建的React应用无法获取Express(PassportJS)发送的Cookie求助

问题解决:Vite React应用无法接收PassportJS认证Cookie

是的,需要修改Vite配置文件来解决这个问题,核心原因是Vite开发服务器的代理默认不携带跨域请求凭证,而CRA的代理配置默认处理了这一点。

解决步骤:

  1. 修改Vite配置文件,添加带凭证的代理设置
    在你的vite.config.js中添加server.proxy配置,显式开启withCredentials,确保请求转发时携带Cookie:

    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    export default defineConfig({
      plugins: [react()],
      server: {
        proxy: {
          // 替换为你的后端API前缀,比如'/api'
          '/api': {
            target: 'http://localhost:3001', // 替换为你的后端服务地址
            changeOrigin: true,
            withCredentials: true // 关键配置:允许跨域请求携带凭证
          }
        }
      }
    })
    
  2. 确保前端请求携带凭证
    无论你用fetch还是axios发起认证请求,都要开启凭证携带:

    • 使用fetch的示例:
      fetch('/api/auth/login', {
        method: 'POST',
        credentials: 'include', // 携带Cookie
        body: JSON.stringify(loginData),
        headers: {
          'Content-Type': 'application/json'
        }
      })
      
    • 使用axios的示例:
      axios.post('/api/auth/login', loginData, {
        withCredentials: true
      })
      

为什么CRA可以正常工作?

CRA的package.json中配置proxy字段后,内部的代理服务器会自动处理跨域凭证的转发,而Vite需要显式配置withCredentials才能实现相同效果。

额外确认(可选)

虽然你用CRA时后端正常,但可以再确认后端Cookie的配置:

  • 确保httpOnly、secure(生产环境)、SameSite属性设置合理,比如跨域场景下SameSite设为None并配合secure。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:40:58