繁体   English   中英

多个node.js请求

[英]Multiple node.js requests

我的控制器正在使用request包向另一个API发出服务器端HTTP请求。 我的问题是我该如何提出多个请求? 这是我当前的代码:

**更新代码**

module.exports = function (req, res) {
var context = {};
request('http://localhost:3000/api/single_project/' + req.params.id, function (err, resp1, body) {
    context.first = JSON.parse(body);
    request('http://localhost:3001/api/reports/' + req.params.id, function (err, resp2, body2) {
        context.second = JSON.parse(body2); //this line throws 'SyntaxError: Unexpected token u' error
        res.render('../views/project', context);
    });
});

};

我需要再打两个电话,然后将返回的数据发送到我的模板中...

有人可以帮忙吗?

提前致谢!

function makePromise (url) {
  return Promise(function(resolve, reject) {

      request(url, function(err, resp, body) {
        if (err) reject(err);
        resolve(JSON.parse(body));
      });

  });
}

module.exprts = function (req, res) {
  let urls = ['http://localhost:3000/api/1st', 
              'http://localhost:3000/api/2st',
              'http://localhost:3000/api/3st'].map((url) => makePromise(url));

  Promise
    .all(urls)
    .then(function(result) {
      res.render('../views/project', {'first': result[0], 'second': result[1], 'third': result[2]});
    })
    .catch(function(error){
      res.end(error);
    });
}

您可以在最新的nodejs中使用Promise lib。

简单的解决方案

嵌套请求调用。 这样可以处理请求之间的依赖关系。 只需确保您的参数在所有作用域中都是唯一的即可。

module.exports = function (req, res) {
    var context = {};
    request('http://localhost:3000/api/1st', function (err, resp1, body) {
        var context.first = JSON.parse(body);
        request('http://localhost:3000/api/2nd', function (err, resp2, body) {
            context.second = JSON.parse(body);
            request('http://localhost:3000/api/3rd', function (err, resp3, body) {
                context.third = JSON.parse(body);
                res.render('../views/project', context);
            });
        });
    });
};

如果使用bluebird promise库,最简单的方法是:

var Promise = require('bluebird');
var request = Promise.promisify(require('request'));

module.exports = function (req, res) {
  var id = req.params.id;
  var urls = [
   'http://localhost:3000/api/1st/' + id,
   'http://localhost:3000/api/2st/' + id,
   'http://localhost:3000/api/3st/' + id
  ];

  var allRequests = urls.map(function(url) { return request(url); });

  Promise.settle(allRequests)
    .map(JSON.parse)
    .spread(function(json1, json2, json3) {
      res.render('../views/project', { json1: json1 , json2: json2, json3: json3  });
    });
});

即使一个(或多个)失败,它也会执行所有请求

暂无
暂无

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

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