webpack反向代理proxyTable设置
如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!
webpack反向代理proxyTable设置
目前各大打包工具在本地开发时都是使用的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插件可以知悉实现代理细节:
- 根据context和pathname来判断是否需要进行代理。
function matchSingleStringPath(context, uri) {
var pathname = getUrlPathName(uri);
return pathname.indexOf(context) === 0;
}
返回时true的时候才会对其进行代理
对于http://www.baidu.com/ttt
这种,在获取配置的时候会进行额外处理,源码如下:
else if (isStringShortHand(context)) {
const oUrl = url.parse(context);
const target = [oUrl.protocol, '//', oUrl.host].join('');
config.context = oUrl.pathname || '/';
config.options = Object.assign(config.options, { target }, opts);
if (oUrl.protocol === 'ws:' || oUrl.protocol === 'wss:') {
config.options.ws = true;
}
// app.use('/api', proxy({target:'http://localhost:9000'}));
}
所以最后认为context仍是/ttt
,并且前面的http://www.baidu.com
会作为target使用,但是一般会被options.target
给覆盖掉。
'\\.\\w*$'
会根据new Regex变成正则表达式/\.\w*$/
。变成rule
{
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);
}
- 分类:
- Web前端
更新时间:
上一篇:下一篇: