Calling already defined routes in other routes in Express NodeJS

為{幸葍}努か 提交于 2019-11-29 10:48:16

问题


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 example
    var html = "<html><body></body></html>"; 
    res.end(html)
});

How do I reuse that route from within express?

app.get("/secondService/:query", function(req,res){
    var data = app.call("/firstService/"+query);
    //do something with the data
    res.end(data);
});

I couldn't find anything in the API documentation and would rather not use another library like "request" because that seems kludgey. I am trying to keep my app as modular as possible. Thoughts?

Thanks


回答1:


Can you simply break this out into another function, put it in a shared spot and go from there?

var queryHandler = require('special_query_handler'); 
// contains a method called firstService(req, res);

app.get('/firstService/:query', queryHandler.firstService);

// second app
app.get('/secondService/:query', queryHandler.secondService);

Honestly, this whole business of nesting the call back inside of the app.get(...) is not really a great practice. You end up with a giant file containing all of the core code.

What you really want is a file filled with app.get() and app.post() statements with all of the callback handlers living in different, better organized files.




回答2:


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 = "<html><body></body></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;



回答3:


If you have a lot of middleware on your route, you can benefit from spreading:

const router = express.Router();

const myMiddleware = [
    authenticationMiddleware(),
    validityCheckMiddleware(),
    myActualRequestHandler
];

router.get( "/foo", ...myMiddleware );
router.get( "/v1/foo", ...myMiddleware );



回答4:


You can use run-middleware module exactly for that

app.runMiddleware('/firstService/query',function(responseCode,body,headers){
     // Your code here
})

More info:

  • Module page in Github & NPM;
  • Examples of use run-middleware module

Disclosure: I am the maintainer & first developer of this module.




回答5:


I have used following way: at userpage.js

router.createSitemap = function(req, res, callback) {  code here callback(value);  }

at product.js

var userPageRouter = require('userpages'); 
userPageRouter.createSitemap(req, res, function () {
                            //console.log('sitemap');
                        });

Also can use in same userpage.js router I can use for other routing as well. eg.

router.get('/sitemap', function (req, res, next) {
    router.createSitemap(req, res, function () {
        res.redirect('/sitemap.xml');
    }); });

Hope this will help.



来源:https://stackoverflow.com/questions/12737371/calling-already-defined-routes-in-other-routes-in-express-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!