Calling already defined routes in other routes in Express NodeJS

后端 未结 5 1501
傲寒
傲寒 2020-12-29 20:11

I am writing a web app in node.js using Express. I have defined a route as follows:

app.get(\"/firstService/:query\", function(req,res){
    //trivial exampl         


        
5条回答
  •  时光说笑
    2020-12-29 20:45

    Similar to what Gates said, but I would keep the function(req, res){} in your routes file. So I would do something like this instead:

    routes.js

    var myModule = require('myModule');
    
    app.get("/firstService/:query", function(req,res){
        var html = myModule.firstService(req.params.query);
        res.end(html)
    });
    
    app.get("/secondService/:query", function(req,res){
        var data = myModule.secondService(req.params.query);
        res.end(data);
    });
    

    And then in your module have your logic split up like so:

    myModule.js

    var MyModule = function() {
        var firstService= function(queryParam) {
            var html = ""; 
            return html;
        }
    
        var secondService= function(queryParam) {
            var data = firstService(queryParam);
            // do something with the data
            return data;
        }
    
        return {
            firstService: firstService
           ,secondService: secondService
        }
    }();
    
    module.exports = MyModule;
    

提交回复
热议问题