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

React-Vite代理配置不生效:请求未转发至目标服务器求助

Vite代理配置不生效,请求未转发到目标服务器问题排查

问题背景

已在vite.config.ts中配置代理规则,将/api开头的请求转发到http://localhost:10000,同时编写了对应的API调用代码,但开发环境下请求仍指向本地http://127.0.0.1:5173/api/...,未按预期转发到目标服务器。

配置代码

vite.config.ts

server: {
    proxy: {
        '/api': {
            target: 'http://localhost:10000',
            changeOrigin: true,
            secure: false,
            ws: true,
            rewrite: path => path.replace('/api', ''),
            configure: (proxy, _options) => {
                proxy.on('error', (err, _req, _res) => {
                  console.log('proxy error', err);
                });
                proxy.on('proxyReq', (proxyReq, req, _res) => {
                  console.log('Sending Request to the Target:', req.method, req.url);
                });
                proxy.on('proxyRes', (proxyRes, req, _res) => {
                  console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
                });
              },
        },
    },
},

API调用代码

import axios from 'axios';

const API_BASE_URL = import.meta.env.MODE === 'development'
  ? '/api/Slave/v1/Permissions'
  : `${import.meta.env.VITE_API_BASE_URL}/Slave/v1/Permissions`;

const PermissionController = {
  getFlatStructure: async (token: string) => {
    try {
      const response = await axios.get(`${API_BASE_URL}/MenusStructure/Flat`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      return response.data;
    } catch (error) {
      console.error('API GET Error:', error);
      throw error;
    }
  }
};

export default PermissionController;

排查与解决方案

1. 重启Vite开发服务器

Vite配置文件修改后必须重启服务器才能生效,很多时候代理不生效只是因为没重启。先停掉当前服务,重新执行npm run dev或yarn dev。

2. 检查axios全局配置

如果项目中设置了axios.defaults.baseURL,可能会覆盖当前的请求路径。检查是否有类似代码:

axios.defaults.baseURL = 'http://127.0.0.1:5173';

如果有,开发环境下需要将其改为''或'/api',或者直接移除全局baseURL配置,改用当前的API_BASE_URL。

3. 修正rewrite规则

当前的rewrite: path => path.replace('/api', '')可能存在匹配问题,比如路径中如果有多个/api会被全部替换。建议改为只替换开头的/api:

rewrite: (path) => path.replace(/^\/api/, '')

确保只有路径最开始的/api被替换,避免意外修改路径中的其他部分。

4. 验证代理是否匹配请求

打开浏览器DevTools的Network标签,查看请求的实际URL:

  • 确认请求URL确实是以/api/Slave/v1/Permissions/MenusStructure/Flat开头,没有被其他代码修改为相对路径或其他地址。
  • 查看控制台是否打印了代理配置中的日志(Sending Request to the Target等),如果没有打印,说明代理规则根本没匹配到请求,需要检查路径是否符合/api开头的规则。

5. 简化代理配置测试

暂时移除configure中的日志和ws等非必要配置,用最基础的代理规则测试是否生效:

server: {
  proxy: {
    '/api': {
      target: 'http://localhost:10000',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, '')
    }
  }
}

如果简化后代理生效,再逐步加回secure、ws、configure等配置,排查是否是某个配置项导致的问题。

6. 清除浏览器缓存

浏览器可能缓存了旧的请求响应或路径规则,按下Ctrl+Shift+R(Windows)或Cmd+Shift+R(Mac)强制刷新页面,清空缓存后再测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:55:07