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);

2 Answers 2

72

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It was the per-route approach I was after. Thanks for the extensive explanation
in this example, is there a one-liner to apply all middlewares.js in app.js?
Only answer/explanation on the topic that made sense to me after a couple days struggling with the issue when learning node.js. Amazing.
4

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
};

1 Comment

yeah "appropriate set of parameters" is the trick :) I haven't fully grasped the export/require relationship yet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.