Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
dev.pus Avatar asked Jun 28 '12 11:06

dev.pus


2 Answers

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.

like image 57
Pavan Kumar Sunkara Avatar answered Oct 22 '22 13:10

Pavan Kumar Sunkara


First, in order to use director you need to wrap it up as a middleware and pass it to express, like so:

app.use(function (req, res, next) {
  router.dispatch(req, res, function (err) {
    if (err) {
      // handle errors however you like. This one is probably not important.
    }
    next();
  });
};

Aside from that: You don't need director to use resourceful, and express has its own router (so you may not even need/want director).

like image 26
Josh Holbrook Avatar answered Oct 22 '22 11:10

Josh Holbrook