首页 > 解决方案 > 如何进行双重请求?

问题描述

如何在 Nodejs 中进行双重请求?

function script() {
  request(`https://hacker-news.firebaseio.com/v0/item/8863.json`, function
  (error, res, body) {
    if(error) {
      console.log(error)
    } else {
      console.log(JSON.parse(body))
    }
  })

}

这是我的代码,我想再次请求查找标题。有人有想法吗?

标签: node.js

解决方案


最简单的方法是在第一个请求的回调函数中发出请求。

function script() {
  request('https://hacker-news.firebaseio.com/v0/item/8863.json', function (error, res, body) {
    if (error) {
      console.log(error);
    } else {
      console.log(JSON.parse(body));
      var titleUrl = '';
      request(titleUrl, function (err, res, body) {
        if (err) {
          console.log(err);
        } else {
          console.log(JSON.parse(body));
        }
      });
    }
  });
}

这对于简单的应用程序来说很好,但它很快就会变得笨拙和丑陋。我建议学习 Promise API。您将需要一个不同的请求库,request因为它本身不支持 Promises。根据经验,如果可以的话,我建议使用got.

function script() {
  got('https://hacker-news.firebaseio.com/v0/item/8863.json')
    .then(function (response) {
      console.log(JSON.parse(response.body));
      let titleUrl = "";
      return got(titleUrl)
    })    
    .then(function(response) {
      console.log(JSON.parse(response.body));
    })
    .catch(function (error) {
      console.log(error);
    });
}

推荐阅读