使用 vue-cli 或者 webpack 开发时,配置 devServer 需要重启才能生效。但日常业务开发中,经常遇到切换后端地址联调的情况,而且公司的电脑配置不高,重启项目可能会很慢,本文讲介绍不重启切换 proxy 的地址的方法实践。
原理
devServer: {proxy: {'api/*': {target: 'localhost',changeOrigin: true,secure: false}}},
devServer 中 依赖了 http-proxy-middleware,平时都是配置 target为后端地址,但是还有个配置项[router](https://github.com/chimurai/http-proxy-middleware#router-objectfunction)可以重写target的地址(target配置项不能删除,会报错),基于此配置项可以实现热切换代理地址。
实现
在项目根目录增加两个文件:
proxy.switch.jsproxy.confg.json修改文件:
```javascript const { getRouter, getReq } = require(‘./proxy.switch.js’);vue.config.js
//… devServer: { proxy: { ‘api/*’: { // 修改 proxy.confg.json,切换 target和加 headers,无需重启 target: ‘localhost’, changeOrigin: true, secure: false, router: getRouter, onProxyReq: getReq } } } //…
<a name="wjsbD"></a>### 主文件:`proxy.switch.js````javascriptconst { readFileSync } = require('fs');const { resolve } = require('path');/*** @desc 配置文件说明* @param {*} target 要使用的目标地址,可以是routers中的key或地址* @param {*} routers 常用的后端服务地址* @param {*} token 直连平台使用的 X-CSRF-TOKEN* @param {*} cookie 直连平台使用的 Cookie*/const configPath = './proxy.confg.json';const cache = {current: '',cookie: '',token: ''};/*** @desc 读取配置*/function getConfig() {try {const jsonStr = readFileSync(resolve(__dirname, configPath), 'utf-8');const confg = JSON.parse(jsonStr);return confg;} catch {console.log('get proxy.config.json failed');}}/*** @desc 动态切换proxy target 无需重启devServer*/function getRouter() {const { target, routes, cookie, token } = getConfig();const current = routes[target] || target;if (cache.current !== current) {console.log(`switch-proxy-target: ${target}(${current})`);}cache.current = current;cache.cookie = cookie;cache.token = token;return current;}/*** @desc 加headers*/function getReq(proxyReq) {const { cookie, token } = cache;proxyReq.setHeader('X-CSRF-TOKEN', token);proxyReq.setHeader('Cookie', cookie);}module.exports = {getRouter,getReq};
配置文件:proxy.confg.json
{"target": "105","routes": {"105": "https://10.19.134.105","20": "https://10.19.215.20","161": "https://10.19.141.161",},"token": "94a517ac-7346-44f2-a915-546084c0a879","cookie": "mNdoncxONxOhzf4i7WuocFmAUx4x0ZL-cas"}
通过 proxy.config.json,可以保存常用的后端服务地址,通过修改 target,无需重启即可实现代理地址的切换
如果直接连接平台环境还需要 Cookie和 X-CSRF-TOKEN,通过F12查看平台上的接口,修改 json 里对应的配置即可。
总结
本文介绍了前端开发过程中,如何不重启热切换代理地址,解决开发过程中的痛点,已应用于业务开发中。
