Search code examples
node.jsexpressflatiron.js

How can I use director as router in expressjs


I want to use express.js with Flatiron's director (router) and Resourceful (ODM) because I need like the benefits of routing tables and clean multi-db schemas with validation. The reason why I now completly switch to Flatiron is, is because I think it needs some more time and there is not much doc material.

However, that is the current way I use director in express:

var express = require('express')
  , director = require('director');

function hello(){
    console.log('Success');
}

var router = new director.http.Router({
    '/': {
        get: hello
    }
});

Unfortunatly this doesn't work and gives me just a "Cannot GET /"

So what's to do?


Solution

  • var express = require('express')
      , director = require('director')
      , http = require('http');
    
    var app = express();
    
    var hello = function () {
      this.res.send(200, 'Hello World!');
    };
    
    var router = new director.http.Router({
      '/': {
        get: hello
      }
    });
    
    var middleware = function (req, res, next) {
      router.dispatch(req, res, function (err) {
        if (err == undefined || err) next();
      });
    };
    
    app.configure(function(){
      app.set('port', process.env.PORT || 3000);
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
    
      app.use(express.favicon());
      app.use(express.bodyParser());
    
      app.use(middleware);
    
      app.use(express.static(__dirname + '/public'));
    });
    
    http.createServer(app).listen(app.get('port'), function(){
      console.log("Express server listening on port " + app.get('port'));
    });
    

    There is a sample app using express, resourceful and director here.

    If you have more doubts, you can ask them in our IRC room #nodejitsu on freenode.