32

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

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
user1148710
  • 323
  • 1
  • 3
  • 4
  • Does this answer your question? [Calling Express Route internally from inside NodeJS](https://stackoverflow.com/questions/38946943/calling-express-route-internally-from-inside-nodejs) – abernier Dec 29 '19 at 11:52

5 Answers5

26

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;
Sean Coley
  • 147
  • 1
  • 10
c0deNinja
  • 3,956
  • 1
  • 29
  • 45
16

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.

ryanm
  • 2,239
  • 21
  • 31
Gates VP
  • 44,957
  • 11
  • 105
  • 108
  • 1
    Thank you! I am just an Express beginner who is trying to get a handle on a project that is becoming unwieldy. Any suggestions for intermediate to advanced express tutorials/help sites? – user1148710 Oct 05 '12 at 04:37
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 );
Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138
2

You can use run-middleware module exactly for that

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

More info:

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

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
1

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.

Mudassar
  • 3,135
  • 17
  • 22
Dhiraj
  • 106
  • 6