node.js 从另一条路线快速调用路线内的 GET 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39047270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:30:40  来源:igfitidea点击:

Express call GET method within route from another route

node.jsexpressrun-middleware

提问by asuciu

I have multiple routes. How can I get the data from the user's route (GET method), by calling it within the GET method of the group's route? What is the best way of doing this?

我有多条路线。如何通过在组路由的 GET 方法中调用用户路由(GET 方法)中的数据?这样做的最佳方法是什么?

My app.js looks like this:

我的 app.js 看起来像这样:

var express = require('express');

var routes = require('./routes/index');
var users = require('./routes/users');
var groups = require('./routes/groups');

var app = express();

app.use('/', routes);
app.use('/users', users);
app.use('/groups', groups);

module.exports = app;
app.listen(3000);

Then I have another file routes/users.js:

然后我有另一个文件 routes/users.js:

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('GET ON THE users!');
});

module.exports = router;

And another route routes/groups.js:

另一个路由 routes/groups.js:

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

/* GET groups listing. */
router.get('/', function(req, res, next) {

    // call the get on users and retrieve all data from that request

    res.send('GET for the groups');
});

module.exports = router;

Thank you! :)

谢谢!:)

回答by 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.

您不应该为此使用路由。只需调用负责从 GET 组路由中检索用户的函数,并使用该数据执行您需要的操作。您提出的方式要贵得多,因为您必须进行 http 调用。

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

为简单起见,我假设您的逻辑是同步的,并且数据存储在 data/users.js 中:

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

in routes/users.js:

在路由/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:

在路由/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');
});

回答by conrad10781

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 nothave any overhead from a subsequent HTTP response.

此外,作为“前进”它并没有具备从随后的HTTP响应的任何开销。

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

对于 Express,以下在 4.X 版中可用。可能有其他版本,但我没有检查过。

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)

回答by Aminadav Glickshtein

You can use run-middlewaremodule exactly for that

您可以run-middleware完全为此使用模块

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

More info:

更多信息:

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

披露:我是这个模块的维护者和第一个开发者。

回答by Stavros

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

对于从谷歌来到这里的人。如果您需要点击一个或多个路由并跳过 http 请求,您也可以使用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

您还可以与Promise.all同时运行它们

回答by abernier

I've made a dedicated middleware for this uest, see my detailed answer here: https://stackoverflow.com/a/59514893/133327

我为此制作了一个专用的中间件uest,请在此处查看我的详细答案:https: //stackoverflow.com/a/59514893/133327