Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two Node.js App server together.

I have two apps. which current run in two different ports.

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);

and here is 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);

ok.. it runs separately on two different ports and have no problem.

Now. the story is that, I can only use port 80 for production. System Admin doesn't want to open 3000 nor other ports.

Instead of merging code. (in fact, my real code is a lot. and have different config settings for script1 and script2), what can I do to make both of them on port 80? but calling /s1/output will go to script1, and /s2/output will go to script2?

I am thinking about having another scripts. script80.js that runs on port 80. and it require both script1, and script2.

But, the question is, what should I export from script 1 and script2? should I:

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

and in script80.js, should I do soemthing like that:

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

mmmm

like image 539
murvinlai Avatar asked Nov 29 '22 18:11

murvinlai


1 Answers

If you have domains or subdomains pointing to this server, you can also use the vhost middleware:

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

app.listen(80);

Complete example: https://github.com/expressjs/express/blob/master/examples/vhost/index.js

like image 129
Maurice Avatar answered Dec 05 '22 12:12

Maurice