配置Vite代理本地9000服务返回500错误,求排查方案
Vite代理本地Web服务返回500错误排查
问题描述
本地http://localhost:9000运行着一个Web服务,配置Vite开发服务器(监听http://localhost:5173)将/api路径代理到该服务时,Vite返回500内部服务器错误。
操作步骤
- 创建标准Vue项目:
λ npm create vue@latest Need to install the following packages: create-vue@3.7.5 Ok to proceed? (y) Vue.js - The Progressive JavaScript Framework √ Project name: ... vue-project √ Add TypeScript? ... _No_ / Yes √ Add JSX Support? ... _No_ / Yes √ Add Vue Router for Single Page Application development? ... _No_ / Yes √ Add Pinia for state management? ... _No_ / Yes √ Add Vitest for Unit Testing? ... _No_ / Yes √ Add an End-to-End Testing Solution? » No √ Add ESLint for code quality? ... _No_ / Yes Scaffolding project in C:\tmp\vue-proxy\vue-project... Done. Now run: cd vue-project npm install npm run dev C:\tmp\vue-proxy λ cd vue-project\ && npm install && npm run dev added 25 packages, and audited 26 packages in 53s 3 packages are looking for funding run `npm fund` for details found 0 vulnerabilities > vue-project@0.0.0 dev > vite VITE v4.4.9 ready in 780 ms ➜ Local: http://localhost:5173/ ➜ Network: use --host to expose ➜ press h to show help
- 在
vite.config.js中添加代理配置:
import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), ], server: { proxy: { "/api": "http://localhost:9000" } }, resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } } })
预期结果
λ curl http://localhost:5173/api/ {"message":"Hi there (root)"} λ curl http://localhost:9000 {"message":"Hi there (root)"}
实际结果
λ curl -i http://localhost:5173/api HTTP/1.1 500 Internal Server Error Access-Control-Allow-Origin: * Content-Type: text/plain Date: Sun, 24 Sep 2023 08:26:09 GMT Connection: keep-alive Keep-Alive: timeout=5 Transfer-Encoding: chunked λ curl http://localhost:9000 {"message":"Hi there (root)"}
Vite错误日志
10:22:08 [vite] http proxy error at /api: Error: connect ECONNREFUSED ::1:9000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)
解决方案
1. 强制Vite使用IPv4连接代理目标
错误日志显示Vite尝试通过IPv6地址::1连接9000端口,但你的本地服务可能仅监听了IPv4的127.0.0.1。修改代理配置,将localhost替换为127.0.0.1:
server: { proxy: { "/api": "http://127.0.0.1:9000" } }
2. 调整本地服务监听地址(可选)
如果希望支持IPv6,可以修改9000端口的Web服务配置,让其同时监听IPv4和IPv6地址(例如将监听地址设为0.0.0.0或::)。
3. 路径重写(匹配预期结果)
从预期结果来看,请求/api需要转发到目标服务的根路径/,因此需要添加路径重写规则,去掉/api前缀:
server: { proxy: { "/api": { target: "http://127.0.0.1:9000", rewrite: (path) => path.replace(/^\/api/, "") } } }
内容的提问来源于stack exchange,提问作者Michael Zelensky
相关产品推荐
相关产品推荐

