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

Vite ReactTS项目生产环境Cookie设置与代理失效问题求助

问题分析与解决方案

核心问题根源

Vite 的 server.proxy 配置仅在开发阶段(vite serve)生效,生产环境打包后(vite build),项目是纯静态资源,不会启动代理服务器。你当前的生产环境配置里保留了 server.proxy,但这部分代码完全无效——生产环境下前端的 /api 请求会直接发送到当前部署的域名,而非你指定的目标服务器,导致 Cookie 无法正确传递,功能失效。


解决方案1:部署时配置反向代理(推荐)

根据你使用的部署平台,配置反向代理规则,将 /api 路径转发到目标服务器,确保请求和 Cookie 能正确传递:

  • Nginx 部署:在 Nginx 配置文件中添加:
location /api {
  proxy_pass https://tame-lime-rooster-tie.cyclic.app;
  proxy_set_header Cookie $http_cookie;
  proxy_set_header Host $host;
}
  • Vercel 部署:在项目根目录创建 vercel.json:
{
  "rewrites": [
    {
      "source": "/api/:path*",
      "destination": "https://tame-lime-rooster-tie.cyclic.app/api/:path*"
    }
  ]
}
  • Netlify 部署:在项目根目录创建 netlify.toml:
[[redirects]]
  from = "/api/*"
  to = "https://tame-lime-rooster-tie.cyclic.app/api/:splat"
  status = 200

如果不想用反向代理,需要修改前端请求逻辑,同时配合后端配置跨域:

  1. 修改前端请求地址:把所有 /api/xxx 格式的请求改为直接请求目标服务器域名,比如 https://tame-lime-rooster-tie.cyclic.app/api/xxx
  2. 携带请求凭证:
    • 用 axios 的话:
      axios.defaults.withCredentials = true;
      
    • 用 fetch 的话:
      fetch('https://tame-lime-rooster-tie.cyclic.app/api/xxx', {
        credentials: 'include'
      });
      
  3. 后端必须配置 CORS 头:
    • Access-Control-Allow-Origin: 设置为你前端部署的具体域名(不能用 *,带 Cookie 时不允许通配符)
    • Access-Control-Allow-Credentials: true
    • Access-Control-Allow-Headers: 包含 Cookie 等必要请求头

优化你的 Vite 配置

既然生产环境不需要 server.proxy,可以简化配置避免混淆:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig(({ command, mode }) => {
  const isDev = mode === 'development';
  const baseConfig = {
    plugins: [react({ include: "**/*.tsx" })],
  };

  // 仅开发环境加载代理配置
  if (command === 'serve') {
    baseConfig.server = {
      proxy: {
        '/api': {
          target: isDev ? 'http://localhost:5000' : 'https://tame-lime-rooster-tie.cyclic.app',
          changeOrigin: true,
          configure: (proxy) => {
            proxy.on('proxyReq', (proxyReq, req) => {
              req.headers.cookie && proxyReq.setHeader('cookie', req.headers.cookie);
            });
          },
          secure: false
        }
      }
    };
  }

  return baseConfig;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:50:20