【问题标题】:Http get multiple json files from different API endpoints using node expressHttp使用node express从不同的API端点获取多个json文件
【发布时间】:2013-04-25 11:05:17
【问题描述】:

我正在研究使用 node 从不同 API 端点获取多个 JSON 文件的最有效方法。

基本上我想将每个 JSON 对象存储在一个变量中,并将它们全部发送到 Jade 模板文件进行解析。 通过执行以下操作,我已将其设置为获取 一个 JSON 文件 (jsonFile1):

httpOptions = {
    host: 'api.test123.com',
    path : '/content/food/?api_key=1231241412',
    headers: {
        "Accept": "application/json",
        'Content-Type': 'application/json'
    },
    method: "GET",
    port: 80
}

var jsonFile1;

http.get(httpOptions, function(res) {
    var body = '';

    res.on('data', function(chunk) {
        body += chunk;
    });

    res.on('end', function() {
        jsonFile1= JSON.parse(body)
        console.log("Got response: " + jsonFile1);
    });
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

app.set('views', __dirname);

app.get('/', function(req, res) {
    res.render('home', {
        data: jsonFile1
    });
});

但我真的不想重复所有这些来获取 多个 json 端点并将它们发送到 home 玉模板。

有什么想法可以有效地做到这一点吗?

【问题讨论】:

  • 将每个端点的 httpOptions 放入一个数组中,遍历该数组并对每个对象发出一个 http 请求,将结果保存在另一个数组中,使用该数组渲染模板。
  • 啊。不要以为你有机会提供代码 sn-p 吗?
  • 嗯,我当然可以提供一个简单的例子,但总的来说,如果你展示你已经尝试过什么/你认为你可以如何解决问题,会更容易。
  • 所以@Scotty,我给你一个提示,你想看代码,我花时间给你写一些代码,你不接受我的回答?或者就为什么不提供反馈?

标签: javascript json node.js express pug


【解决方案1】:

根据您的代码,这是一个使用出色的 async 库的快速示例。

var async = require('async'),
    // Array of apis
    httpOptions = [
        {
            host: 'api.test123.com',
            path : '/content/food/?api_key=1231241412',
            headers: {
                "Accept": "application/json",
                'Content-Type': 'application/json'
            },
            method: "GET",
            port: 80
        },
            host: 'api.test234.com',
            path : '/content/food/?api_key=1231241412',
            headers: {
                "Accept": "application/json",
                'Content-Type': 'application/json'
            },
            method: "GET",
            port: 80
        }
    ];

// Put the logic for fetching data in its own function
function getFile(options, done) {
    http.get(options, function(res) {
        var body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            done(null, JSON.parse(body));
            console.log("Got response: " + jsonFile1);
        });
    }).on('error', function(e) {
        done(e);
        console.log("Got error: " + e.message);
    });
}


app.get('/', function(req, res) {
    // Map the options through the getFile function, resulting in an array of each response
    async.map(httpOptions, getFile, function (err, jsonFiles) {
        // You should probably check for any errors here
        res.render('home', {
            data: jsonFiles
        });
    });
});

【讨论】:

  • 在你的例子github.com/mikeal/request中使用request模块也可以简化很多http代码
  • 我最近在想应该有一个像jQuery的.ajax这样的模块,因为很多人问如何通过express来做请求。这些模块似乎很容易使用。
猜你喜欢
  • 2019-09-11
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2016-11-26
相关资源
最近更新 更多