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前端
相关文章
用webpack的require.context() 简化你的代码
随着我们的项目越来越大,平时的常见用操作就会觉得很‘麻烦’了,比如每次要添加新的路由, vuex里面添加新的module等 { name: 'moduleN', 阅读更多…
从vuecli3学习webpack记录(二)webpack分析
上一篇里面讲到运行 npm run serve 时运行的是 serveice.run(comand, args, rawArgv) 并且提到它提示返回的是一个promise,所以后面还接着 .cat 阅读更多…
从vuecli3学习webpack记录(一)vue-cli-serve机制
最近看了看vuecli3,把自己的学习记录下来。 首先看入口 npm run dev 即是 vue-cli-service serve ,之所以能运行 vue-cli-service 命令,就是 阅读更多…
从vuecli3学习webpack记录(零)整体流程
今天看了下自己之前写的从vuecli3学习webpack记录系列,感觉自己居然没有在一开始的时候把vuecli的 npm run serve 的整体流程在一篇文章里面完整的讲完,可能是因为打字打的手 阅读更多…
从vuecli3学习webpack记录(三)基类Tapable和Hook分析
在查看webpack(及插件)源码的过程中,我们会经常看到类似这样的代码 compiler.hooks.done.tap('vue-cli-service serve',( 阅读更多…
从vuecli3学习webpack记录(四)vue是怎么进行默认配置的
在我们讲到 从vuecli3学习webpack记录(一)vue-cli-serve机制 vue cli3中在commands文件夹里面的是调用api.registerCommand方法,在 阅读更多…