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+React项目,报错basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")怎么办
今天在WebStorm上Windows上准备调试一个React项目,就出现了这样的报错。 Node Parameters里面写的是webpack-dev-server的执行文件 .\node_mod 阅读更多…
以webpack为例来看微内核架构
微内核系统一般分为两个部分—— 核心系统 和 插件系统 ,这样就提供了很好的灵活性和可扩展性。 核心系统是最小可运行的模块,它提供的是通用逻辑(比如Tapable),而插件系统这是些具体的逻辑(比如 阅读更多…
从vuecli3学习webpack记录(四)vue是怎么进行默认配置的
在我们讲到 从vuecli3学习webpack记录(一)vue-cli-serve机制 vue cli3中在commands文件夹里面的是调用api.registerCommand方法,在 阅读更多…
从vuecli3学习webpack记录(三)基类Tapable和Hook分析
在查看webpack(及插件)源码的过程中,我们会经常看到类似这样的代码 compiler.hooks.done.tap('vue-cli-service serve',( 阅读更多…
用webpack的require.context() 简化你的代码
随着我们的项目越来越大,平时的常见用操作就会觉得很‘麻烦’了,比如每次要添加新的路由, vuex里面添加新的module等 { name: 'moduleN', 阅读更多…
用webpack的require.context优化vue store和router文件
早期右边博文专门讲了下require.context的用法和简单用法介绍《用webpack的require.context() 简化你的代码》 这次说点自己在vue项目中的具体应用吧 store 阅读更多…