npm install --save express http-proxy
proxy.js
var express = require(‘express‘);var app = express();var httpProxy = require(‘http-proxy‘);var apiProxy = httpProxy.createProxyServer();var serverOne = ‘http://localhost:3001‘, ServerTwo = ‘http://localhost:3002‘;// 访问 http://localhost:3000/server1 时,代理 http://localhost:3001/server1app.all("/server1", function(req, res) { apiProxy.web(req, res, { target: serverOne });});// 访问 http://localhost:3000/server2 时,代理 http://localhost:3002/server2app.all("/server2", function(req, res) { apiProxy.web(req, res, { target: ServerTwo });});// 访问 http://localhost:3000/xxx 时,代理 http://localhost:3001/xxxapp.all("/*", function(req, res) { apiProxy.web(req, res, { target: serverOne });});app.listen(3000);
server.js
const express = require(‘express‘);const server = express();const server2 = express();server.get(‘/*‘, function(req, res) { res.send(`Hello world From Server 1 <br> req.path : ${req.path}`);});server2.get(‘/*‘, function(req, res) { res.send(`Hello world From Server 2 <br> req.path : ${req.path}`);});// serverOneserver.listen(3001);// ServerTwoserver2.listen(3002);
node proxy
,node server
http://localhost:3000/server1
等地址进行测试Reverse proxy using ExpressJS – Codeforgeek