Nodejs request-promise combining json api data from 2 links?

走远了吗. 提交于 2021-01-29 14:00:08

问题


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 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'));

I am trying to combine the 2 json api urls(the data from them), and cant seem to figure out what to do. Do I need to create an array? If so how? So I am trying to combine the data from different urls(because of different regions) all onto one main page that can be accessed.


回答1:


You should definitely not use request-promise anymore since the request-module, on which request-promise depends, has been deprecated. Now, to answer your question.. assuming you're using superagent as a http request-module, you could do:

const request = require('superagent');
const moment = require('moment');

app.get('/', async (req, res) => {
  // responses will be an array of the resolved responses of the two calls
  const responses = await getApi();           
  res.render('home', { api: responses, moment: moment() });
});

function requestApis() {
 return Promise.all([request.get(url),request.get(url2)]);
}


来源:https://stackoverflow.com/questions/64649813/nodejs-request-promise-combining-json-api-data-from-2-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!