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

后端 未结 2 1640
野性不改
野性不改 2020-12-24 14:02

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

相关标签:
2条回答
  • 2020-12-24 14:23

    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.

    0 讨论(0)
  • 2020-12-24 14:28

    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
    };
    
    0 讨论(0)
提交回复
热议问题