Alex Rivera | Logout

Calling already defined routes in other routes in Express NodeJS

Asked 2012-10-04T23:17:55.490
31

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

Edit
Report

1 Answer

15

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.

answered 2012-10-04T23:33:36.913

Your Answer