I am trying to understand how vhost
actually works in Express JS. Here's a working code sample (forgot where I pulled this from):
// -- inside index.js --
var EXPRESS = require('express');
var app = EXPRESS.createServer();
app.use(EXPRESS.vhost('dev.example.com', require('./dev').app));
app.listen(8080);
// -- inside dev.js --
var EXPRESS = require('express');
var app = exports.app = EXPRESS.createServer();
app.get('/', function(req, res)
{
// Handle request...
});
Now, my question is, why do we call createServer()
twice? Why does this even work? Is vhost
internally "merging" the two servers together?
vhost is a NodeJS middleware package that serves as a simple manager to segment traffic to specific services based on the requesting hostname.
Improves on express. js middleware for vhost by avoiding expensive regex chains. This will perform better and scale more than connect vhost. If trust proxy is enabled the X-Forwarded-Host header will be respected, so that the hosts can work behind a remote proxy such as Nginx.
Node.js is event-driven, and when a request comes in, the request
event is raised on a http.Server
. So basically, express.vhost
(or really, connect.vhost
) is a middleware function which raises the request
event on another instance of a http.Server
:
function vhost(req, res, next){
if (!req.headers.host) return next();
var host = req.headers.host.split(':')[0];
if (req.subdomains = regexp.exec(host)) {
req.subdomains = req.subdomains[0].split('.').slice(0, -1);
server.emit('request', req, res);
} else {
next();
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With