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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With