node.js - 如何在expressjs Nodejs中发出嵌套的REST GET请求

标签 node.js rest express

假设我的路由文件具有以下 REST 端点:

app.get('/userlist', function (req, res) {

    var httpClient = addon.httpClient(req);
    httpClient.get('example.com/users',
        function(error, response, body) {
            if (!error && response.statusCode == 200) {

                var users = JSON.parse(body);
                users.forEach(function(user, index, arr) 
                {
                  //do the 2nd REST GET request here using user.id ???
                }

                res.render('userlist', {
                    content : users
                });
            }
        });
}

端点使用 RESTful Web 服务,结果如下所示:

{ users :  [{ id : 12345 },{ id : 23456 },{ id : 34567 }]}

现在我想知道如何/在哪里做第二个。 REST GET 请求 (/userinfo) 用于检索用户的额外信息(基于第一个请求结果中的 user.id)> 并更新第 1 个。结果为第二。

问候

最佳答案

使用仅支持回调的httpClient,最好的选择是为每个步骤创建一个函数并避免深层嵌套的 block :

function findFirstUser(callback) {
  httpClient.get('example.com/users', (error, response, body) => {
    var firstUserId = JSON.parse(body).users[0]
    getUser(firstUserId, callback)
  })
}


function getUser(id, callback) {
  httpClient.get('example.com/users/' + id, callback)
}

async图书馆也可以帮助您做到这一点。

我不推荐这两种方法。相反,请使用支持 PromiseshttpClient,例如 axios :

httpClient.get('example.com/users')
  .then(response => JSON.parse(response.body).users[0])
  .then(userId => httpClient.get('example.com/users/' + userId))
  .catch(error => console.error(error))

关于node.js - 如何在expressjs Nodejs中发出嵌套的REST GET请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41838060/

相关文章:

javascript - mocha 如何递归搜索我的 `src` 文件夹以查找特定的文件名模式?

javascript - 如何读取node.js目录中的文件?

java - 休息/javax/ Jersey /灰熊 : is it mandatory to return OK (200) response code for POST requests?

Javascript:具有多个查询参数的嵌套 JSON api 请求

mysql - sails .js : Waterline foreign key association missing in MySQL

javascript - Jasmine-node 期望未执行

wcf - 使用 Azure ACS 和 OAuth 2.0 的 Facebook 式 API 访问场景 : how to implement app authorization?

jQuery 和 couchdb : is it possible to handle "created" and "already exist" in one handler?

javascript - 访问本地主机:3000 through localhost/myproject/index. html

mysql - 我想从 nodejs 获得对 angular 6 的响应