简体   繁体   中英

nodejs reverse proxy instead of nginx as reverse proxy

I'm developing a web application using nodejs and I need a reverse proxy for this application. In many places it is noticed that nginx is used as a reverse proxy. My questions are 1. "Is there any ready made nodejs based reverse proxy?" 2. "Is it a good idea to implement a nodejs based reverser proxy?" 3. "It is advised to use nginx?" 4. Why is nginx is considered in first place for reverse proxy?

--Ganesh

use following command to install Express.js and http-proxy.

npm install --save express http-proxy

In order to run the reverse proxy server we need some resource server from which Proxy will fetch data.So to do that, develop three Express server running on Port 8000,8001,8002 respectively.

Server.js
var express = require("express");
var app = express();

app.get('/app1',function(req,res) {
res.send("Hello world From Server 1");
});

app.listen(8000); 
write the same code for other servers too and change the text.

Example of proxy server code in express.js with multiple targets.

app.js (file)
var express  = require('express');
var app      = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var serverOne = 'http://localhost:8000',
ServerTwo = 'http://localhost:8001',
ServerThree = 'http://localhost:8002';

app.all("/app1/*", function(req, res) {
  console.log('redirecting to Server1');
apiProxy.web(req, res, {target: serverOne});
});

app.all("/app2/*", function(req, res) {
  console.log('redirecting to Server2');
apiProxy.web(req, res, {target: ServerTwo});
});

app.all("/app2/*", function(req, res) {
   console.log('redirecting to Server3');
apiProxy.web(req, res, {target: ServerThree});
});
app.listen(8000);


You can add as many targets as you want and it will create a proxy for that.Check whether its working or not by first run all the servers and hit request to /app1 and /app2 etc.

I found the DProx node plugin an absolute must. Allows for most of the configuration that one would need from a Reverse proxy server, while making it simple JSON config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM