image.png
devServer: {
port: 8080,
proxy: {
"/api": {
target: "http://xxx:3000",
ws: true,
changeOrigin: true,
pathRewrite: {
"^/api": "",
},
},
hot: true,
}
const onProxyRes = (proxy) => {
for (const api in proxy) {
const {target, ws, changeOrigin, pathRewrite} = proxy[api];
proxy[api] = {
target,
ws: ws || false,
changeOrigin: changeOrigin || false,
pathRewrite: pathRewrite || undefined,
onProxyRes(proxyRes, req) {
try {
const targetObj = new URL(target)
let reqUrl = req.url
if (pathRewrite) {
for (const key in pathRewrite) {
const replaceValue = pathRewrite[key];
let pattern = new RegExp(key)
reqUrl = req.url.replace(pattern, replaceValue)
}
}
let pathname = (targetObj.pathname + reqUrl).replace('//', '/')
const realUrl = new URL(pathname, targetObj.origin)?.href ?? ''
proxyRes.headers['x-real-url'] = realUrl
} catch (error) {
proxyRes.headers['x-real-url'] = 'undefined'
}
}
}
}
return proxy
}
devServer: {
port: 8080,
proxy: onProxyRes({
"/api": {
target: "http://xxx:3000",
ws: true,
changeOrigin: true,
pathRewrite: {
"^/api": "",
},
}),
hot: true,
}
网友评论