分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

Node.js - 使用 Express 和 http-proxy 进行反向代理

发布时间:2023-09-06 02:31责任编辑:董明明关键词:js反向代理httpNode

安装 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/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);

测试

  1. 分别启动 server.js 和 proxy.js:node proxynode server
  2. 浏览器访问http://localhost:3000/server1等地址进行测试

参考

Reverse proxy using ExpressJS – Codeforgeek

Node.js - 使用 Express 和 http-proxy 进行反向代理

原文地址:https://www.cnblogs.com/jffun-blog/p/10327350.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved