Files
qhmes/jeecgboot-vue3/build/vite/proxy.ts

53 lines
1.4 KiB
Vue
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Used to parse the .env.development proxy configuration
*/
import type { ProxyOptions } from 'vite';
type ProxyItem = [string, string];
type ProxyList = ProxyItem[];
type ProxyTargetList = Record<string, ProxyOptions>;
const httpsRE = /^https:\/\//;
/**
* Generate proxy
* @param list
*/
export function createProxy(list: ProxyList = []) {
const ret: ProxyTargetList = {};
for (const [prefix, target] of list) {
const isHttps = httpsRE.test(target);
// 若 target 带路径(如 http://localhost:8080/jeecg-boot需拼回转发路径
// 否则 rewrite 去掉 /jeecgboot 后只剩 /xslmes/...,缺少 context-path后端会报 No static resource。
let proxyTarget = target;
let targetPathPrefix = '';
try {
const u = new URL(target);
const p = (u.pathname || '').replace(/\/$/, '');
if (p) {
targetPathPrefix = p;
proxyTarget = `${u.protocol}//${u.host}`;
}
} catch {
/* 非标准 URL 时保持原 target */
}
// https://github.com/http-party/node-http-proxy#options
ret[prefix] = {
target: proxyTarget,
changeOrigin: true,
ws: true,
rewrite: (path) => {
const stripped = path.replace(new RegExp(`^${prefix}`), '');
return targetPathPrefix ? `${targetPathPrefix}${stripped}` : stripped;
},
// https is require secure=false
...(isHttps ? { secure: false } : {}),
};
}
return ret;
}