簡體   English   中英

如何將兩個 Node.js 應用服務器組合在一起。

[英]How to combine two Node.js App server together.

我有兩個應用程序。 哪個電流在兩個不同的端口中運行。

腳本1.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?

我正在考慮有另一個腳本。 script80.js 在端口 80 上運行。它需要 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) ?
}

嗯嗯

如果您有指向此服務器的域或子域,您還可以使用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

您可以使用 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;
}

您也可以按照您的要求在 express 中手動編寫代碼,但是為什么要重新發明輪子呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM