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
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With