53 lines
1.4 KiB
Vue
53 lines
1.4 KiB
Vue
/**
|
||
* 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;
|
||
}
|