nodejs反向代理而不是nginx作为反向代理

时间:2015-07-02 16:34:41

标签: node.js reverse-proxy

我正在使用nodejs开发一个Web应用程序,我需要一个针对此应用程序的反向代理。 在许多地方,注意到nginx用作反向代理。 我的问题是 1."是否有现成的基于nodejs的反向代理?" 2."实现基于nodejs的反向代理是一个好主意吗?" 3."建议使用nginx?" 4.为什么nginx首先被认为是反向代理?

- 内甚

1 个答案:

答案 0 :(得分:0)

使用以下命令安装Express.js和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.