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

React+Vite应用经代理访问时API请求返回404问题求助

问题描述

我有一个基于Vite构建的React应用,用于调用Node/NestJS API。当通过任意代理站点测试该应用时,API请求无法正常工作,控制台返回404错误。

React应用已部署在Netlify,相关配置如下:

Vite配置

export default defineConfig(({ mode }) => ({
  plugins: [
    react(),
    svgr(),
    tsconfigPaths()
  ],
  resolve: {
    alias: {
      'src': path.resolve(__dirname, './src')
    },
    extensions: ['.js', '.ts', '.jsx', '.tsx']
  },
  build: {
    chunkSizeWarningLimit: 1600
  },
  server: {
    proxy: {
      '/api': {
        target: 'https://test-cms-api.herokuapp.com',
        changeOrigin: true,
        secure: false
      }
    }
  }
}))

NestJS服务端配置

app.use(cookieParser(jwtSecret));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

// 错误处理中间件
app.use(
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  (err: Error, request: Request, response: Response, next: NextFunction) => {
    handleError(err, response);
  },
);

app.use(
  session({
    secret: jwtSecret,
    resave: false,
    saveUninitialized: false,
    store: new session.MemoryStore(),
    cookie: {
      httpOnly: true,
      signed: true,
      sameSite: 'strict',
      secure: process.env.NODE_ENV === 'production',
    },
  }),
);
app.use(passport.initialize());
app.use(passport.session());

app.enableCors({
  origin: '*',
  credentials: true,
  exposedHeaders: ['Authorization'],
});

app.setGlobalPrefix('api/');

app.useGlobalPipes(
  new ValidationPipe({
    exceptionFactory: validationExceptionFactory,
  }),
);

process.env.NODE_ENV !== 'production' && Swagger({ app });
await app.listen(process.env.PORT);

原本期望应用能在任意代理环境下正常运行,此前用react-scripts构建时页面无法渲染,换成Vite后页面渲染问题解决,但API请求仍失败。


问题原因与解决方案

核心原因

  1. Vite代理仅生效于开发环境:server.proxy配置只在本地开发服务器中起作用,生产构建后的应用部署到Netlify后,该规则不会被应用。此时前端发起的/api请求会被发送到代理站点的域名,而非你的后端API地址,导致404。
  2. Cookie跨域限制:服务端设置了sameSite: 'strict'的Cookie规则,在代理这种跨域场景下,Cookie无法被正常携带,可能进一步影响API的身份验证流程(即使请求地址修复,后续也可能出现权限错误)。

解决方案

1. 生产环境使用绝对API地址

通过Vite环境变量区分开发/生产环境的API地址,避免相对路径导致的请求错误:

  • 在项目根目录创建.env.production:
    VITE_API_BASE_URL=https://test-cms-api.herokuapp.com/api
    
  • 创建.env.development保留开发代理:
    VITE_API_BASE_URL=/api
    
  • 前端代码中使用环境变量拼接请求路径:
    const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
    
    // 示例请求
    fetch(`${API_BASE_URL}/your-endpoint`)
      .then(res => res.json())
      .then(data => console.log(data));
    

2. 调整Cookie的SameSite配置

修改NestJS的session Cookie规则,适配跨域代理场景:

cookie: {
  httpOnly: true,
  signed: true,
  sameSite: process.env.NODE_ENV === 'production' ? 'lax' : 'strict', 
  // 若需完全跨域代理下携带Cookie,可改为'none',但必须确保secure: true(你的后端是HTTPS,符合要求)
  secure: process.env.NODE_ENV === 'production',
},

3. Netlify配置生产代理(可选)

如果希望前端继续使用相对路径/api,可在Netlify中通过_redirects文件实现代理:
在项目public目录下创建_redirects文件:

/api/*  https://test-cms-api.herokuapp.com/api/:splat  200

Netlify会自动将所有/api开头的请求转发到你的后端API地址。

验证步骤

  1. 修改配置后重新构建并部署React应用到Netlify。
  2. 通过代理站点访问应用,检查网络请求的目标地址是否正确指向后端API。
  3. 验证API请求是否返回正常响应,同时确认身份相关请求的Cookie是否正常携带。

内容的提问来源于stack exchange,提问作者Alessandra De Paula

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:05:14