29

I am new to the whole Node.js thing, so I am still trying to get the hang of how things "connect".

I am trying to use the express-form validation. As per the docs you can do

app.post( '/user', // Route  
  form( // Form filter and validation middleware
    filter("username").trim()
  ),

  // Express request-handler gets filtered and validated data
  function(req, res){
    if (!req.form.isValid) {
      // Handle errors
      console.log(req.form.errors);

    } else {
      // Or, use filtered form data from the form object:
      console.log("Username:", req.form.username);

    }
  }
);

In App.js. However if I put something like app.get('/user', user.index); I can put the controller code in a separate file. I would like to do the same with the validation middleware (or put the validation code in the controller) to make the App.js file easier to overview once I start adding more pages.

Is there a way to accomplish this?

Basically I would like to put something like app.get('/user', validation.user, user.index);

danneth
  • 2,721
  • 1
  • 23
  • 31

2 Answers2

71

This is how you define your routes:

routes.js:

module.exports = function(app){
    app.get("route1", function(req,res){...})
    app.get("route2", function(req,res){...})
}

This is how you define your middlewares:

middlewares.js:

module.exports = {
    formHandler: function(req, res, next){...}
}

app.js:

// Add your middlewares:
middlewares = require("middlewares");
app.use(middlewares.formHandler);
app.use(middlewares...);

// Initialize your routes:
require("routes")(app)

Another way would be to use your middleware per route:

routes.js:

middlewares = require("middlewares")
module.exports = function(app){
    app.get("route1", middlewares.formHandler, function(req,res){...})
    app.get("route2", function(req,res){...})
}

I hope I answer your questions.

Jean-Philippe Leclerc
  • 6,713
  • 5
  • 43
  • 66
  • It was the per-route approach I was after. Thanks for the extensive explanation – danneth Feb 19 '13 at 17:41
  • 2
    in this example, is there a one-liner to apply all middlewares.js in app.js? – 4m1r Mar 12 '15 at 00:14
  • Only answer/explanation on the topic that made sense to me after a couple days struggling with the issue when learning node.js. Amazing. – mkvlrn Feb 09 '16 at 20:43
3

You can put middleware functions into a separate module in the exact same way as you do for controller functions. It's just an exported function with the appropriate set of parameters.

So if you had a validation.js file, you could add your user validation method as:

exports.user = function (req, res, next) {
  ... // validate req and call next when done
};
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • yeah "appropriate set of parameters" is the trick :) I haven't fully grasped the export/require relationship yet – danneth Feb 19 '13 at 17:42