简体   繁体   中英

how to make nested REST GET requests in expressjs nodejs

Let's say my route file has the following REST endpoint:

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

The endpoint consumes an RESTful webservice and the result looks like this:

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

Now i would like to know how / where to do the 2nd. REST GET request ( /userinfo ) to retrieve extra information of the user (based on the user.id from the result of the 1st. request) and update the 1st. result with 2nd.

Regards

Using an httpClient that only supports callbacks, your best bet is to create a function for each step and avoid deeply nested blocks:

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

The async library can help you do this as well.

I do not recommend either approach. Instead, use an httpClient that supports Promises , such as 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM