道招

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插件可以知悉实现代理细节:

  1. 根据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给覆盖掉。

  1. '\\.\\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);
}
更新时间:
上一篇:vuex的mapState mapActions mapMutations mapGetters在模块module使用详解下一篇:使用discord或者slack的api实现自己的翻译bot

相关文章

从vuecli3学习webpack记录(一)vue-cli-serve机制

最近看了看vuecli3,把自己的学习记录下来。 首先看入口 npm run dev 即是 vue-cli-service serve ,之所以能运行 vue-cli-service 命令,就是 阅读更多…

用webpack的require.context优化vue store和router文件

早期右边博文专门讲了下require.context的用法和简单用法介绍《用webpack的require.context() 简化你的代码》 这次说点自己在vue项目中的具体应用吧 store 阅读更多…

webpack笔记——在html-webpack-plugin插件中提供给其它插件是使用的hooks

最近在这段时间刚好在温故下webpack源码,webpack5都出来了,4还不再学习下? 这次顺便学习下webpack的常用插件html-webpack-plugin。 发现这个插件里面还额外加入了 阅读更多…

webpack笔记——hook执行时call的是什么

我们一般使用的插件都是Hook子类,比如SyncHook,没有复杂的重写基类Hook的compile方法 先看Hook基类 // node_module/tapable/Hook.js cla 阅读更多…

用webpack的require.context() 简化你的代码

随着我们的项目越来越大,平时的常见用操作就会觉得很‘麻烦’了,比如每次要添加新的路由, vuex里面添加新的module等 { name: 'moduleN', 阅读更多…

从vuecli3学习webpack记录(四)vue是怎么进行默认配置的

在我们讲到 从vuecli3学习webpack记录(一)vue-cli-serve机制 vue cli3中在commands文件夹里面的是调用api.registerCommand方法,在 阅读更多…

关注道招网公众帐号
友情链接
消息推送
道招网关注互联网,分享IT资讯,前沿科技、编程技术,是否允许文章更新后推送通知消息。
允许
不用了