将多个开发服务代理至同一端口访问

业务场景:使用vue-cli开发的三个网站,开发时启动了端口的服务,登录后cookie、localStorage等数据无法共享访问,需要通过URL传参,非常的麻烦(生成环境部署到同一域名,不存在该问题)。

解决办法:将多个开发热更新服务(webpack-dev-server/vue-cli devServer),代理至同一端口进行访问,共享子系统间的cookie等存储数据

/**
 * 将多个开发热更新服务(webpack-dev-server/vue-cli devServer),代理至同一端口进行访问,共享子系统间的cookie等存储数据
 */
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const open = require('open')

const ProxyPort = 8080 // 代理服务IP
const config = require('../packages/hi-fas-utils/proxy.config')
const app = express();
// 静态资源托管,docker下存在index.html,且自动执行window.open('/platform/', '_self')跳转
app.use(express.static('./docker'));
// 注册路由
app.get('/', function(req, res) {})

/**
 * 网站代理
 */
// 特殊处理:直接URL引入的第三方js库, 目录platform/public/lib
app.use(createProxyMiddleware(['/lib'], {
    target: `http://${config.host}:${config.port.platform}/platform`,
    changeOrigin: true,
    ws: true
}));
// 子系统:devServer服务,地址xxx.xxx.xxx.xxx:[port]/platform
app.use(createProxyMiddleware(['/platform/**'], {
    target: `http://${config.host}:${config.port.platform}`,
    changeOrigin: true,
    ws: true
}));
// 子系统:devServer服务,地址xxx.xxx.xxx.xxx:[port]/manage
app.use(createProxyMiddleware(['/manage/**'], {
    target: `http://${config.host}:${config.port.manage}`,
    changeOrigin: true,
    ws: true
}));
// 子系统:devServer服务,地址xxx.xxx.xxx.xxx:[port]/station
app.use(createProxyMiddleware(['/station/**'], {
    target: `http://${config.host}:${config.port.station}`,
    changeOrigin: true,
    ws: true
}));
/**
 * 接口代理
 */
app.use('/api/', createProxyMiddleware({
    target: config.proxyUrl,
    changeOrigin: true,
    pathRewrite: {
        '^/api/': ''
    }
}));

// 启动服务
const server = app.listen(ProxyPort, config.host, () => {
    const port = server.address().port
    console.log("代理应用实例,访问地址为 http://%s:%s", config.host, port)
    open(`http://${config.host}:${port}`)
});

 修改开发调试指令:

1     "dev-serve": "start yarn workspace manage run dev && start yarn workspace platform run dev && start yarn workspace station run dev", // 启动调试服务
2     "dev-proxy": "start node script/proxy.js", // 启动代理服务
3     "dev": "npm run dev-serve && npm run dev-proxy" // 开发调试指令

最后只需要执行npm run dev即可同时启动开发服务,而后将服务进行代理访问,使用8080端口即可访问三个子系统的服务了。

posted @ 2022-05-11 11:49  Hxxxxxxyyyyyy  阅读(152)  评论(0编辑  收藏  举报