结合nodejs中2个URL的json数据?

问题描述

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,似乎无法弄清楚该怎么做。我需要创建一个数组吗?如果可以,怎么办?因此,我试图将来自不同网址(由于区域不同)的数据全部组合到一个可以访问的主页上。

解决方法

每个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 */
}