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

配置Vite代理转发Flask后端失败:请求仍指向Vite端口排查

Vite代理配置后fetch请求仍指向本地端口的问题

我正在运行部署于localhost:5173的Vite应用,需要请求部署于localhost:5000的Flask服务器数据。所有API端点在Postman中均可正常调用,但按Vite官方文档配置代理后,fetch请求仍指向localhost:5173。

我的vite.config.ts配置

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "http://127.0.0.1:5000",
        changeOrigin: true,
        secure: false,
        ws: true,
        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);
          });
        }
      },
    }
  }
})

代理日志输出

Sending Request to the Target: GET /api/home/
Received Response from the Target: 200 /api/home/

fetch请求代码

fetch('/api/home')
  .then((res) => console.log(res))
// .then((res) => res.json())
// .then((data: object[]) => {
//   setPostData(data)
// })

控制台输出(显示请求指向本地端口)

type: 'basic', 
url: 'http://localhost:5173/api/home/', 
redirected: true, 
status: 200,  ok: true, …

Postman返回的数据示例

[{
        "comments": [],
        "created_at": "Thu, 23 Mar 2023 08:30:17 GMT",
        "likes": 2,
        "text": "Lorem ipsum",
        "title": "Morbi non quam nec dui luctus rutrum",
        "updated_at": "Thu, 23 Mar 2023 08:30:17 GMT",
        "user": "alesmonde0",
        "user_id": 1
    }]

我刚接触Flask和TypeScript,但有React/Vite搭配Express和Node的开发经验,是不是有什么简单的细节被我忽略了?

已尝试的解决方法

  • 严格遵循Vite官方文档配置代理
  • 将server.proxy路径改为'/' - 结果仅显示Flask应用,无法访问Vite前端页面
  • 在vite.config中添加secure: false - 无效果
  • 在vite.config中添加ws: true - 无效果
  • 为fetch请求添加Access-Control-Allow-Origin请求头 - 无作用
  • 添加server.proxy.configure选项排查错误 - 但返回200状态码,与预期的400不符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:15:15