基于nodejs开发的web工程开启代理转发功能

来源:互联网 发布:java程序员周末班 编辑:程序博客网 时间:2024/06/07 15:21

背景:
web开发中,我们需要访问mock server则需要把web中所有请求代理到mockserver中。

在启动web开发模式的脚本中,添加以下代码。其中a-api是一个访问路径。

const proxy = require('http-proxy-middleware');//引入代理中间件const aProxy = proxy('/a-api', { target: 'http://127.0.0.1:7001',changeOrigin: true });const bProxy = proxy('/b-api', { target: 'http://127.0.0.1:7001',changeOrigin: true });var options = {        target: 'http://127.0.0.1:7001',          changeOrigin: true,            pathRewrite: {            '^/server-api/app' : '/app'                    }    };这里是把/server-api/app/* 请求 转发到http://127.0.0.1:7001/appconst apiProxy = proxy(options);app.use('/server-api/app/*',apiProxy);app.use('/a-api/*',apiProxy);app.use('/b-api/*',serverApiProxy);