【问题标题】:Combining json data from 2 urls in nodejs?在nodejs中结合来自2个url的json数据?
【发布时间】:2020-11-02 05:08:39
【问题描述】:
const express = require('express');
const app     = express();
const path    = require('path');
const config  = require('./config.json');
const moment = require('moment');

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

url = 'https://ne.api.site',
url2 = 'https://n2.api.site',


app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));

async function getApi(){
  return request({
        url : url,
        url2 : url2
    });

}


/* Routes */
app.get('/', async (req, res) => {
  let host = req.get('host');
  let api = await getApi();
  let json = await JSON.parse(api);
  res.render('home', { api: json, moment: require('moment')});
});


app.listen(4800, () => console.log('Express listening on port 4800'));

我正在尝试组合 2 个 json api url,但似乎无法弄清楚该怎么做。我需要创建一个数组吗?如果有怎么办?因此,我试图将来自不同 url(因为不同区域)的数据全部合并到一个可以访问的主页上。

【问题讨论】:

标签: node.js json request-promise


【解决方案1】:

每个 API 都需要自己单独的 GetAPI 操作。确实没有将来自多个 API 端点的数据检索合并为一个这样的事情。

你已经在使用异步函数,所以你可以试试这个伪代码。

async function isOnline(name){
  const result = {};
  let api   = await getFirstApi();
  let json  = JSON.parse(api);
  result.firstApi = json;
  api   = await getSecondApi();
  json  = JSON.parse(api);
  result.secondApi = json;
  /* whatever comes next */
}

【讨论】:

  • 不能让它工作,你能用这个重写我的代码吗?谢谢帮助
  • getFirstApi 将是仅具有第一个 URL 的 getApi,而 getSecondApi 将具有第二个 URL
猜你喜欢
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多