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

Vite+React+Flask代理失效:前端请求未转发至后端

Vite代理配置失败排查与解决

问题场景

尝试在前端配置Vite代理,通过fetch()调用后端Flask API,但请求始终走Vite默认端口5173而非后端的3001端口,返回500错误。添加代理事件监听后,发现连接被拒绝,错误提示connect ECONNREFUSED ::1:3001。

现有配置

vite.config.ts

server: {
  proxy: { "/api":  {
                    target: 'http://localhost:3001',
                    changeOrigin: true,
                    secure: false      
                    }
           }
},

前端代码(frontend.tsx)

const Test: React.FC = () => {
  useEffect(()=>{
    fetch(`api/hello`)
    .then(res => console.log(res))
  }, [])
  return(
  <div>
    hi
  </div>
  )
}

后端Flask代码

@app.route('/api/hello', methods=['GET'])
def test():
    return jsonify({"hi":"there"})

错误信息

  1. 初始请求错误:
GET http://localhost:5173/api/hello net::ERR_ABORTED 500 (Internal Server Error)
  1. 添加代理监听后的错误日志:
Sending Request to the Target: GET /api/hello
proxy error Error: connect ECONNREFUSED ::1:3001
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 3001
}
3:45:38 p.m. [vite] http proxy error at /api/hello:
Error: connect ECONNREFUSED ::1:3001
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) (x3)

解决步骤

1. 确认后端服务状态

ECONNREFUSED是典型的“无法连接目标服务”错误,先排查后端:

  • 确保Flask服务已启动,且明确监听3001端口:
    if __name__ == '__main__':
        app.run(port=3001, debug=True)
    
  • 直接在浏览器访问http://localhost:3001/api/hello,验证是否能正常返回{"hi":"there"}。

2. 修正Vite代理的目标地址(解决IPv6兼容问题)

错误日志显示代理尝试连接IPv6地址::1:3001,但部分情况下Flask默认只监听IPv4的127.0.0.1。修改vite.config.ts中的target为明确的IPv4地址:

server: {
  proxy: { 
    "/api":  {
      target: 'http://127.0.0.1:3001', // 用127.0.0.1替代localhost
      changeOrigin: true,
      secure: false
    }
  }
},

3. 修正前端fetch请求路径

确保fetch的路径以/开头,避免相对路径解析错误:

fetch(`/api/hello`) // 路径前添加/

4. 重启Vite开发服务器

修改vite.config.ts后必须重启服务,新配置才能生效。

验证

重启服务后,前端的/api/hello请求会被代理到http://127.0.0.1:3001/api/hello,后端正常响应后,前端控制台会打印出包含正确JSON数据的响应对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:32:50