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

React 19(Vite)+FastAPI前端API请求代理配置异常求助

问题排查与解决方案

1. 检查Axios的baseURL配置

Axios未正确设置baseURL时,会默认以当前页面域名(前端端口)发起请求,需确认配置:

  • 在Axios实例文件(如src/utils/axios.js)中指定baseURL:
    import axios from 'axios';
    
    const api = axios.create({
      // 开发环境用Vite代理,生产环境用后端服务地址或Nginx代理地址
      baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api',
      timeout: 10000,
    });
    
  • 验证环境变量文件(.env.development/.env.production)的配置,注意变量必须以VITE_开头才能被Vite识别:
    # .env.development(开发时用Vite代理)
    VITE_API_BASE_URL=/api
    
    # .env.production(Docker环境用服务名,本地部署用后端地址)
    VITE_API_BASE_URL=http://backend:8000/api
    

2. 配置Vite开发环境代理

开发时需通过Vite代理解决跨域,确保vite.config.js的代理规则正确:

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

export default defineConfig({
  plugins: [react()],
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:8000', // Docker环境下替换为后端服务名(如http://backend:8000)
        changeOrigin: true,
        // 若后端接口不带/api前缀,需添加rewrite规则:rewrite: (path) => path.replace(/^\/api/, '')
      },
    },
  },
});

配置后,前端请求/api/v1/profile会自动转发到http://localhost:8000/api/v1/profile。

3. 检查生产环境Nginx配置

生产环境用Nginx反向代理时,需添加API转发规则到nginx.conf:

server {
  listen 80;
  server_name localhost;

  # 前端静态文件路由
  location / {
    root /usr/share/nginx/html;
    try_files $uri $uri/ /index.html;
  }

  # API请求转发到后端
  location /api {
    proxy_pass http://backend:8000; // Docker环境用服务名,本地部署用http://localhost:8000
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

4. 验证Docker Compose服务关联

确保前后端服务在同一网络,且后端服务名配置正确:

version: '3.8'
services:
  frontend:
    build: ./frontend
    ports:
      - "5173:80"
    depends_on:
      - backend
    networks:
      - app-network

  backend:
    build: ./backend
    ports:
      - "8000:8000"
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

容器内访问后端需用服务名(如backend)而非localhost,容器的localhost指向自身而非主机。

5. 清理缓存与验证

  • 开发环境:修改配置后重启Vite服务,避免缓存导致旧配置生效;打开浏览器Network面板,确认请求URL是否被正确转发。
  • 生产环境:重新构建前端镜像,确保环境变量被正确打包;进入前端容器执行echo $VITE_API_BASE_URL,验证变量加载情况;用curl http://localhost:5173/api/v1/profile测试Nginx转发是否正常。

内容的提问来源于stack exchange,提问作者HUY PHAM MINH

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:05:03