Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put middleware in it's own file in Node.js / Express.js

Tags:

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

like image 574
danneth Avatar asked Feb 19 '13 13:02

danneth


People also ask

Can we use middleware in node JS?

With Node. js middleware, you can run any code and modify the request and response objects. You can also call for the next middleware in the stack when the current one is completed. The example below will help you with the process of creating your Node.

How is an Express middleware added what is it passed?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.


Video Answer


1 Answers

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.

like image 132
Jean-Philippe Leclerc Avatar answered Oct 26 '22 22:10

Jean-Philippe Leclerc