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 = requir开发者_JS百科e('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
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
You can use nginx listening on port 80 and reverse proxying traffic to the 2 different express app servers behind it.
location /s1/ {
rewrite /s1(.*) $1 break;
proxy_pass http://localhost:3000;
}
location /s2/ {
rewrite /s2(.*) $1 break;
proxy_pass http://localhost:3001;
}
You could also code this by hand in express as you are asking about, but why reinvent the wheel?
精彩评论