Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 548
user1148710 Avatar asked Oct 04 '12 23:10

user1148710


People also ask

How do you call a function in Express route?

Just take the code that figures out what the data response is for the /users route and put it in a separate function. Then call that function from both of the places you want to use it. If it's async, then make the function return a promise that gets resolved with the data.

Which method enables to redirect a route in Express?

In express, we can use the res. redirect() method to redirect a user to the different route. The res. redirect() method takes the path as an argument and redirects the user to that specified path.

How do Middlewares work in Express?

Middleware literally means anything you put in the middle of one layer of the software and another. Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to.


1 Answers

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; 
like image 77
c0deNinja Avatar answered Sep 22 '22 19:09

c0deNinja