繁体   English   中英

在我的情况下如何发出 http 请求?

[英]How to make http requests in my case?

我正在尝试使用 NodeJs 请求模块链接 http 请求。

例子:

var options = {
  url: 'http://example.com'
};

request.get(options, function(error, response, body){
  var first = JSON.parse(body);

  options.url = 'http://example.com/second' + first.id;

  //nested second request
  request.get(options, function(error, response, body){
    var second = JSON.parse(body);

    options.url = 'http://example.com/third' + second.title;

    //another nested request
    request.get(options, function(error, response, body){
      var third = JSON.parse(body);
      return third;
    });
  })
})

有没有更好的方法来实现链式承诺?

Request 库不直接支持承诺 您可以使用request-promise (如果使用 ES6,则使用request-promise-native )将 Promise 与request一起使用:

// run `npm install request request-promise` first

var request = require('request-promise');

var options = {
  uri: 'http://example.com',
  json: true // Automatically parses the JSON string in the response
};

request.get(options).then(function(body){
  //second request
  options.url = 'http://example.com/second' + body.id;    
  return request.get(options)
}).then(function(body){
  //third request
  options.url = 'http://example.com/third' + body.title;
  return request.get(options)
}).then(function(body){
  return body;
}).catch(function(error){
  // error handling
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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