1

I am sorta new to node.js and web programming in general so excuse if I ask strange questions :D

So here is the way I am setting up my express node.js project.
I have a top level app.js simply to redirect traffic to a few subdomains:

var app = module.exports = express.createServer(options);
app.use(express.vhost('blog.localhost', require('./apps/blog/blog.js')));
app.use(express.vhost('app1.localhost', require('./apps/app1/app1.js')));
app.use(express.vhost('login.localhost', require('./apps/login/login.js')));

In each of the sub-apps, that is included via require(), I simply return a new express server:

module.exports = express.createServer(options);

What is the most elegant way to set up a 404 page? When I was just using a single app, I simply used

app.use(function(req, res, next){
  res.render('404', {
  });
});

But if I use this method, I am going to have to create a 404.jade for every app and I dislike useless duplications in code. Any idea how to share a single 404 logic across multiple vhosts?

1 Answers1

0

You have 3 hosts that require 3 route files. My suggestion is to require in each this 404 route, from an external file. This way you would have the 404 route for every host, but it will just reside in one place.

Example:

404 route file - 404.js

module.exports = function (app, req, res, options) {
  app.get('/404', function(req, res, next) {
    res.render('404', { options: options });
  });
}

routes for host A

// define other routes here
...
// you pass the app, req, res as params
// the last param is for local vars sent to the view
require('./routes/404.js')(app, req, res, { host: 'HostA' });
alessioalex
  • 62,577
  • 16
  • 155
  • 122
  • Thanks for the quick response. I was trying to avoid this kind of dependency because then the app running in host A has to know the directory structure of the main app. Maybe this is the only way to achieve this. – user1131735 Jan 05 '12 at 22:58
  • Unless you want to duplicate this everywhere, it's the only way. – alessioalex Jan 06 '12 at 12:45