Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How can I use director as router in expressjs

How can I use director as router in expressjs

Problem

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?

Problem courtesy of: dev.pus

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.

Solution courtesy of: Pavan Kumar Sunkara

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How can I use director as router in expressjs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×