2026-01-16 13:06:44 +08:00
|
|
|
|
import type { ProxyOptions } from 'vite'
|
|
|
|
|
|
import { consola } from 'consola'
|
|
|
|
|
|
import { bgRed, bgYellow, green, lightBlue } from 'kolorist'
|
|
|
|
|
|
import { createServiceConfig } from '../../src/utils/service'
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
2026-01-22 17:55:35 +08:00
|
|
|
|
* 设置 HTTP 代理
|
2026-01-16 13:06:44 +08:00
|
|
|
|
*
|
2026-01-22 17:55:35 +08:00
|
|
|
|
* @param env - 当前环境变量
|
|
|
|
|
|
* @param enable - 是否启用 HTTP 代理
|
2026-01-16 13:06:44 +08:00
|
|
|
|
*/
|
|
|
|
|
|
export function createViteProxy(env: Env.ImportMeta, enable: boolean) {
|
|
|
|
|
|
const isEnableHttpProxy = enable && env.VITE_HTTP_PROXY === 'Y'
|
|
|
|
|
|
|
|
|
|
|
|
if (!isEnableHttpProxy)
|
|
|
|
|
|
return undefined
|
|
|
|
|
|
|
|
|
|
|
|
const isEnableProxyLog = env.VITE_PROXY_LOG === 'Y'
|
|
|
|
|
|
|
|
|
|
|
|
const { baseURL, proxyPattern, other } = createServiceConfig(env)
|
|
|
|
|
|
|
|
|
|
|
|
const proxy: Record<string, ProxyOptions> = createProxyItem({ baseURL, proxyPattern }, isEnableProxyLog)
|
|
|
|
|
|
|
|
|
|
|
|
other.forEach((item) => {
|
|
|
|
|
|
Object.assign(proxy, createProxyItem(item, isEnableProxyLog))
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
return proxy
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-22 17:55:35 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 创建 HTTP 代理项
|
|
|
|
|
|
*
|
|
|
|
|
|
* @param item - 服务配置项
|
|
|
|
|
|
* @param enableLog - 是否启用日志记录
|
|
|
|
|
|
*/
|
2026-01-16 13:06:44 +08:00
|
|
|
|
function createProxyItem(item: App.Service.ServiceConfigItem, enableLog: boolean) {
|
|
|
|
|
|
const proxy: Record<string, ProxyOptions> = {}
|
|
|
|
|
|
|
|
|
|
|
|
proxy[item.proxyPattern] = {
|
|
|
|
|
|
target: item.baseURL,
|
|
|
|
|
|
changeOrigin: true,
|
2026-01-28 08:33:36 +08:00
|
|
|
|
secure: false, // 如果是https接口,需要配置这个参数
|
2026-01-16 13:06:44 +08:00
|
|
|
|
configure: (_proxy, options) => {
|
|
|
|
|
|
_proxy.on('proxyReq', (_proxyReq, req, _res) => {
|
|
|
|
|
|
if (!enableLog)
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2026-01-22 17:55:35 +08:00
|
|
|
|
const requestUrl = `${lightBlue('[代理地址]')}: ${bgYellow(` ${req.method} `)} ${green(`${item.proxyPattern}${req.url}`)}`
|
2026-01-16 13:06:44 +08:00
|
|
|
|
|
2026-01-22 17:55:35 +08:00
|
|
|
|
const proxyUrl = `${lightBlue('[真实请求地址]')}: ${green(`${options.target}${req.url}`)}`
|
2026-01-16 13:06:44 +08:00
|
|
|
|
|
|
|
|
|
|
consola.log(`${requestUrl}\n${proxyUrl}`)
|
|
|
|
|
|
})
|
|
|
|
|
|
_proxy.on('error', (_err, req, _res) => {
|
|
|
|
|
|
if (!enableLog)
|
|
|
|
|
|
return
|
2026-01-22 17:55:35 +08:00
|
|
|
|
consola.log(bgRed(`错误: ${req.method} `), green(`${options.target}${req.url}`))
|
2026-01-16 13:06:44 +08:00
|
|
|
|
})
|
|
|
|
|
|
},
|
|
|
|
|
|
rewrite: path => path.replace(new RegExp(`^${item.proxyPattern}`), ''),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return proxy
|
|
|
|
|
|
}
|