簡體   English   中英

如何在express.js node.js中嵌套REST GET請求

[英]how to make nested REST GET requests in expressjs nodejs

假設我的路由文件具有以下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並更新第一個。 結果與第二。

問候

使用僅支持回調的httpClient ,最好的選擇是為每個步驟創建一個函數並避免深度嵌套的塊:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM