// vite.config.ts
server: {
host: true,
port: VITE_PORT,
proxy: createProxy(VITE_PROXY),
},
import type { ProxyOptions } from 'vite';
type ProxyItem = [string, string];
type ProxyList = ProxyItem[];
type ProxyTargetList = Record<string, ProxyOptions & { rewrite: (path: string) => string }>;
export function createProxy(list: ProxyList = []) {
const ret: ProxyTargetList = {};
for (const [prefix, target] of list) {
ret[prefix] = {
target: target,
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
};
}
return ret;
}
开发配置:
// env.dev
VITE_PROXY = [["/dev","http://localhost:37290"]]
# API 接口地址
VITE_GLOB_API_URL = /dev
测试环境配置:
// env.test
VITE_PROXY = [["/test","http://localhost:37290"]]
# API 接口地址
VITE_GLOB_API_URL = /test
开发和测试都是连本地的后端,开发时使用vite --mode dev
,代理可以正常使用。
测试环境是使用vite build --mode test
打包之后用vite preview
运行,出现请求没有发送到后端,却报200的情况,我把后端关掉也是200:
如果我把proxy写死,重新打包,代理就正常了:
server: {
host: true,
port: VITE_PORT,
// proxy: createProxy(VITE_PROXY),
proxy: {
'/test': {
target: 'http://localhost:37290',
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace(/^\/test/, ''),
},
},
},
后端关掉,前两次请求红了;运行后端之后可以正常获取数据。
有大神知道为什么吗?