Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding vhost in Express Node.js

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?

like image 314
pixelfreak Avatar asked Mar 03 '12 20:03

pixelfreak


People also ask

What is vhost in NodeJS?

vhost is a NodeJS middleware package that serves as a simple manager to segment traffic to specific services based on the requesting hostname.

What is vhost Express?

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.


1 Answers

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();
    }
  };
like image 169
Linus Thiel Avatar answered Oct 05 '22 05:10

Linus Thiel