数码资讯
Node.js - 使用 Express 和 http-proxy 进行反向代理
选购提示
关注价格、性能、续航、售后和真实使用场景,理性比较后再下单。
安装 Express 和 http-proxy
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/server1
app.all("/server1", function(req, res) {
apiProxy.web(req, res, {
target: serverOne
});
});
// 访问 http://localhost:3000/server2 时,代理 http://localhost:3002/server2
app.all("/server2", function(req, res) {
apiProxy.web(req, res, {
target: ServerTwo
});
});
// 访问 http://localhost:3000/xxx 时,代理 http://localhost:3001/xxx
app.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}`);
});
// serverOne
server.listen(3001);
// ServerTwo
server2.listen(3002);
测试
- 分别启动 server.js 和 proxy.js:
node proxy,node server - 浏览器访问
http://localhost:3000/server1等地址进行测试
参考
Reverse proxy using ExpressJS – Codeforgeek
声明:本文内容用于数码产品信息整理与选购参考,具体价格、库存、售后政策以官方渠道和电商页面实时信息为准。