NodeJS请求多个api端点 [英] NodeJS request multiple api endpoints

查看:146
本文介绍了NodeJS请求多个api端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我试图使用请求模块向API端点发出两个或更多的请求。我正在渲染一个HTML文件,并使用以下代码将返回的JSON传递给一个句柄模板:

Ok so I am trying to make two or more requests to API endpoints using the request module. I am rendering a HTML file and passing the returned JSON to a handlebars template using the below code:

res.render('list.html', {
  title: 'List',
  data: returnedJSON
}

我可以很容易地在我的手柄模板中迭代这个JSON。

I can then iterate over this JSON within my handlebars template fairly easily.

我遇到的问题是我现在需要使用多个数据来源的类别列表将从类JSON应用程序和员工JSON响应中的员工列表构建。我想要一个简单的解决方案,我可以做到这一点,但扩展它使用任何数量的数据源。

The problem I have, is that I am now needing to use multiple data sources where a category list will be built from a categories JSON response and a Staff list from a staff JSON response. I would like a simple solution where I can do this, but expand it to use any number of data sources.

以下是一个完整的代码片段,其中包含一个数据源:

Below is a full code snippet of what I have with one data source:

request({
    url: 'https://api.com/categories',
    headers: {
        'Bearer': 'sampleapitoken'
    }
}, function(error, response, body) {
    if(error || response.statusCode !== 200) {
        // handle error
    } else {
        var json = JSON.parse(body);
        res.render('list.html', {
            title: 'Listing',
            data: json
        });
    }
});

这对一个端点非常有用,但如前所述,我现在需要使用多个请求并具有多个数据来源例如:

This works great for one endpoint, but as mentioned before I now need to use multiple requests and have multiple data sources for example:

request({
    url: ['https://api.com/categories','https://api.com/staff'],
    headers: {
        'Bearer': 'sampleapitoken'
    }
}, function(error, response, body1, body2) {
    if(error || response.statusCode !== 200) {
        // handle error
    } else {
        var json1 = JSON.parse(body1);
        var json2 = JSON.parse(body2);
        res.render('list.html', {
            title: 'Listing',
            staff: json1,
            categories: json2
        });
    }
});

我感谢以上不行,但我希望这可以帮助我传达尝试实现。

I appreciate the above doesn't work like that, but I hope this can help convey what I am trying to achieve.

提前感谢:)

推荐答案

你可以使用异步库映射您的请求对象并将其传递给实际请求,并将所有结果返回一个回调。

You can use the async library to map your request objects and pass them to an actual request and return all results in one callback.

var async = require("async");
var request = require("request");

// create request objects
var requests = [{
  url: 'https://api.com/categories',
  headers: {
    'Bearer': 'sampleapitoken'
  }
}, {
  url: 'https://api.com/staff',
  headers: {
    'Bearer': 'sampleapitoken'
  }
}];

async.map(requests, function(obj, callback) {
  // iterator function
  request(obj, function(error, response, body) {
    if (!error && response.statusCode == 200) {
      // transform data here or pass it on
      var body = JSON.parse(body);
      callback(null, body);
    } else {
      callback(error || response.statusCode);
    }
  });
}, function(err, results) {
  // all requests have been made
  if (err) {
    // handle your error
  } else {
    console.log(results);
    for (var i = 0; i < results.length; i++) {
      // request body is results[i]
    }
  }
});






然而,一种更简单的方法就是利用承诺,可以用bluebird和promisify请求lib来完成,或使用已经承诺的请求lib 请求承诺 。您仍然希望包含承诺/ A + lib以异步映射结果。


However a simpler way would to leverage promises, this can be done with bluebird and promisifying the request lib, or use the already promisified request lib request-promise. You'll still want to include a promise/A+ lib to map the results asynchronously.

var Promise = require("bluebird");
var request = require('request-promise');

// create request objects
var requests = [{
  url: 'https://api.com/categories',
  headers: {
    'Bearer': 'sampleapitoken'
  }
}, {
  url: 'https://api.com/staff',
  headers: {
    'Bearer': 'sampleapitoken'
  }
}];

Promise.map(requests, function(obj) {
  return request(obj).then(function(body) {
    return JSON.parse(body);
  });
}).then(function(results) {
  console.log(results);
  for (var i = 0; i < results.length; i++) {
    // access the result's body via results[i]
  }
}, function(err) {
  // handle all your errors here
});






重要的是要注意所有最新版本的节点浏览器支持Promise开箱即用,无需外部库即可实现。


It's important to note that all latest versions of node and browsers support Promises out of the box and this can be implemented without external libraries.

这篇关于NodeJS请求多个api端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆