webpack反向代理proxyTable設定
阿新 • • 發佈:2018-12-21
目前各大打包工具在本地開發時都是使用的http-proxy-middleware外掛
具體以vue為例,反向代理配置的就是proxyTable
proxyTable: { 'http://www.baidu.com/ttt': { target: 'http://localhost:1333', changeOrigin: true, pathRewrite: { '\\.\\w*$': '~okkk', } }, '/user': { target: 'http://localhost:1333', changeOrigin: true, pathRewrite: { '/user': 'ppqq', } } },
最終會變成
{ context:'http://www.baidu.com/ttt', options:{ target: 'http://localhost:1333', changeOrigin: true, pathRewrite: { '\\.\\w*$': '~okkk', } } }, { context:'/user', options:{ target: 'http://localhost:1333', changeOrigin: true, pathRewrite: { '/user': 'ppqq', } } },
檢視http-proxy-middleware外掛可以知悉實現代理細節:
1. 根據context(會根據url.parse獲取到pathname,例如'http://www.baidu.com/ttt'實際使用的是'/ttt')來判斷是否需要進行代理。
function matchSingleStringPath(context, uri) {
var pathname = getUrlPathName(uri);
return pathname.indexOf(context) === 0;
}
返回時true的時候才會對其進行代理
2. '\\.\\w*$'
會根據new Regex變成正則表示式/\.\w*$/
{
regex: /\.\w*$/,
value: '~okkk'
}
根據請求的path(req.url)開始匹配,在中介軟體過程中更改req.url為替換後的result
let result = path;
if (rule.regex.test(path)) {
result = result.replace(rule.regex, rule.value);
}