user1148710 user1148710 - 1 year ago 88
Node.js Question

Calling already defined routes in other routes in Express NodeJS

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>";

How do I reuse that route from within express?

app.get("/secondService/:query", function(req,res){
var data ="/firstService/"+query);
//do something with the 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?


Answer Source

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.firstService);

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 statements with all of the callback handlers living in different, better organized files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download