Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've been experimenting with the Express Node.js framework. On the face of it, the approach of passing functions to app.VERB methods seems unusual. In other frameworks I've used (in languages other than javascript), you create a single handler class for each url pattern, with methods representing different HTTP verbs. One advantage is the ability to bundle common functionality in methods of superclasses.

I've tried to replicate this in node, but I'm interested in feedback on whether this seem like a good approach.

(I realise that the naming of "as_view" doesn't make much sense - I just named it that way because I'm used to django, where the term "view" is used to refer to something akin to a controller rather than a template.)

function Controller(verbs) {
    for (verb in verbs) {
        this[verb] = verbs[verb];
Controller.prototype.as_view = function() {
    var dispatcher = function(req, res) {
        var verb = req.method.toLowerCase();
        this[verb](req, res);
    return dispatcher.bind(this);

var pageone = new Controller({

    get: function(req, res) {
        res.send("Get request");

    post: function(req, res) {
        res.send("Post request");


app.all('/pageone', pageone.as_view()); 
share|improve this question
You might want to take a look at express.js version 4. There is a function called route in the router. – jackdbernier Mar 9 '14 at 16:26

This looks good to me,

  • As you mentioned, as_view stands out a bit, but I see where you are coming from
  • I am not sure why you do not declare GET and POST, then you do not need to use toLowerCase(), are you worried the caller will now uppercase the verbs?
  • You should think about error handling, you should have some framework for it

All in all, I would still suggest that learning and using Express.js might be worth it.

share|improve this answer

Follow up on my comment.

Here's some examples (shamelessly taken from here

    .get(function(req, res, next) {
          //do stuff
    .post(function(req, res, next) {
         // do stuff    


var dogs = express.Router();
dogs.get('/', function(req, res, next) {
    // doing more stuff 
});'/', function(req, res, next) {

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.