起因:最近vite项目突然开始出问题,代理的后端api频频报错500
环境:node -v22.12.0 vite -v7.0.0
vcode:powershell 报错:
[vite] http proxy error: *****
Error: connect ETIMEDOUT 24**:**:**:**:**:**:c1**3:c**c:1443
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1615:16)
报错情况分析:
不同的api:
- 其他api地址代理正常(https://api.***.cn/q**/)
- 只有(https://oa.***.cn:1443/q**/)报错
不同的node版本:
- 使用老项目(node -v14.19.1 webpack-dev-server -v2.9.1)
- 代理过后,访问api一切正常
根据vite仓库讨论区得知:
根因是node 17以后修改了dns resolution order,默认将localhost解析为ipv6的": :1"。
但如果你的后端服务监听地址是localhost:xxxx,这就导致了不匹配
ps:运维把服务器配置的 localhost 替换为 127.0.0.1,也是一种解决方案(未经测试)
但是这篇文章是从前端的角度出发,解决这个问题
我的处理如下:强制使用Ipv4:
import https from 'node:https'
agent: new https.Agent({ family: 4 })
ps:本人使用的后台api是https,如果你使用的是http,如下:
import http from 'node:http'
agent: new http.Agent({ family: 4 })
//vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import https from 'node:https'
export default defineConfig({
server: {
open: true,
port: 8088,
proxy: {
'/api': {
target: 'https://abc.abc123.cn:1443/api/',
ws: true,
changeOrigin: true,
agent: new https.Agent({ family: 4 }),
rewrite: (path) => path.replace(/^\/api/, '')
},
},
})
也有另外一种处理方法:(没办法处理本人这种情况)
import https from 'node:https'
agent:new https.Agent({ keepAlive: true, keepAliveMsecs: 20000 })