【问题标题】:How to combine two Node.js App server together.如何将两个 Node.js 应用服务器组合在一起。
【发布时间】:2011-07-28 22:56:45
【问题描述】:

我有两个应用程序。哪个电流在两个不同的端口中运行。

script1.js:

var express = require('express'),
    app = require('express').createServer(

         express.cookieParser(),
          // Parses x-www-form-urlencoded request bodies (and json)
          express.bodyParser()  
    )
    ;

app.get('/s1/output', function(sReq, sRes){
    // set cookie

    sRes.send('<div>Out from 1!</div>');
});

app.listen(3000);

这里是 script2.js

var express = require('express'),
    app = require('express').createServer(

         express.cookieParser(),
          // Parses x-www-form-urlencoded request bodies (and json)
          express.bodyParser()  
    )
    ;

app.get('/s2/output', function(sReq, sRes){
    // set cookie

    sRes.send('<div>Out from 2!</div>');
});
app.listen(3001);

好的..它分别在两个不同的端口上运行,没有问题。

现在。故事是,我只能使用端口 80 进行生产。系统管理员不想打开 3000 也不想打开其他端口。

而不是合并代码。 (事实上​​,我的真实代码很多。并且对 script1 和 script2 有不同的配置设置),我该怎么做才能让它们都在端口 80 上?但是调用 /s1/output 会转到 script1,而 /s2/output 会转到 script2?

我正在考虑制作另一个脚本。在端口 80 上运行的 script80.js。 它需要 script1 和 script2。

但是,问题是,我应该从脚本 1 和脚本 2 导出什么?我应该:

define all get / post methods, and then, 
module.exports.app =app?

在 script80.js 中,我应该这样做吗:

app.get('/s1/*', function (res, req)) {
   // and what do now?  app1(res) ?
}

mmmm

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    如果您有指向此服务器的域或子域,也可以使用vhost 中间件:

    app.use(express.vhost('s1.domain.com', require('s1').app));
    app.use(express.vhost('s2.domain.com', require('s2').app));
    
    app.listen(80);
    

    完整示例:https://github.com/expressjs/express/blob/master/examples/vhost/index.js

    【解决方案2】:

    您可以使用 nginx 侦听端口 80 并将流量反向代理到其后面的 2 个不同的快速应用服务器。

    location /s1/ {
        rewrite /s1(.*) $1 break;
        proxy_pass http://localhost:3000;
    }
    
    location /s2/ {
        rewrite /s2(.*) $1 break;
        proxy_pass http://localhost:3001;
    }
    

    您也可以按照您的要求手动编写代码,但为什么要重新发明轮子?

    【讨论】:

      猜你喜欢
      • 2017-12-17
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多