Express call GET method within route from another route

随声附和 提交于 2019-11-30 18:38:24
Slawomir Pasko

You shouldn't use routing for that. Just call the function responsible for retrieving the users from the GET groups route and do what you need with that data. The way you propose is much more expensive because you will have to make a http call.

For simplicity I'm assuming that your logic is synchronous and data stored in data/users.js:

var data = [{id:1, name: "one"},{id: 2, name: "two"}];
module.exports = function(){
  return data;
};

in routes/users.js:

var express = require('express');
var router = express.Router();
var getUsers = required('./../data/users');

router.get('/', function(req, res, next) {
  res.send(getUsers());
});

in routes/groups.js:

var express = require('express');
var router = express.Router();
var otherRouter = require('./users')
var getUsers = require('./.../data/users');

router.get('/', function(req, res, next) {
  var users = getUsers();
  //do some logic to get groups based on users variable value
  res.send('GET for the groups');
});

I consider what was being explained "forwarding", and it's quite useful, and available in other frameworks, in other languages.

Additionally, as a "forward" it does not have any overhead from a subsequent HTTP response.

In the case of Express, the following is available in version 4.X. Possibly other versions, but I have not checked.

var app = express()

function myRoute(req, res, next) {
  return res.send('ok')
}

function home(req, res, next) {
   req.url = '/some/other/path'

   // below is the code to handle the "forward".
   // if we want to change the method: req.method = 'POST'        
   return app._router.handle(req, res, next)
}

app.get('/some/other/path', myRoute)
app.get('/', home)

You can use run-middleware module exactly for that

app.runMiddleware('/pathForRoute',{method:'post'},function(responseCode,body,headers){
     // Your code here
})

More info:

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

For people coming here from google. If you need to hit one or more of your routes and skip the http request you can also use supertest.

const request = require("supertest");

app.get("/usersAndGroups", async function(req, res) {
    const client = request(req.app);
    const users = await client.get("/users");
    const groups = await client.get("/groups");

    res.json({
        users: users.body,
        groups: groups.body
    });
});

You can also run them concurrently with Promise.all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!