import type { ProxyOptions } from 'vite' type ProxyItem = [string, string] type ProxyList = ProxyItem[] type ProxyTargetList = Record const proxyList: ProxyList = [['/api', 'http://localhost:8301/api']] /** * 创建代理配置 * @param base 项目根路径,必须以“/”结尾,例如“/base/” * @param debug 是否开启调试模式,打印请求信息 */ export function createProxy(base?: string, debug?: boolean) { const ret: ProxyTargetList = {} for (const [prefix, target] of proxyList) { const isHttps = target.startsWith('https://') const completePrefix = base ? base.replace(/\/+$/, '') + prefix : prefix // https://github.com/http-party/node-http-proxy#options ret[completePrefix] = { target: target, changeOrigin: true, ws: true, rewrite: (path) => path.replace(new RegExp(`^${completePrefix}`), ''), // https is require secure=false ...(isHttps ? { secure: false } : {}), configure: debug ? (proxy, options) => { proxy.on('proxyReq', (proxyReq, req, res, options) => { console.log( '---------------------------------proxyReq----------------------------------', ) console.log(proxyReq.path) }) proxy.on('proxyRes', (proxyRes, req, res) => { console.log( '---------------------------------proxyRes----------------------------------', ) console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, null, 2)) }) proxy.on('error', function (err, req, res) { console.log('error : ', err) }) } : undefined, } } return ret }