How to combine JSON data from multiple APIs using a NodeJS server

I have a NodeJS server that receives data from three different APIs and then sends JSON from three APIs to my interface. Since I marked the data from the three APIs differently, it is sent in three different arrays (could there be an incorrect term here?). I am trying to send all this into one array, if possible!

The code:

var express = require('express');
var router = express.Router();
var request = require('request');
var app = express();

router.get("/", function(req, res){
var request = require('request-promise');
var data1;
var data2;
var data3;


request("http://api1.com").then(function(body){
data1 = JSON.parse(body);

return request("http://api2.com");
})
.then(function(body) {
    data2 = JSON.parse(body);


    return request("http://api3.com");
})
.then(function(body){
    data3 = JSON.parse(body);

    res.json("services.ejs", {data1: data1, data2: data2, data3: data3});
  })
});

module.exports = router;

Result:

{"data1":[{All JSON from API #1}] - "Data2":[{All JSON from API #2}] - "Data3":[{All JSON from API #3}]}

Required Result:

{"allData": [{All JSON from API #1 #2 #3}]}

+4
source share
1 answer

You can combine 3 different results together into one array:

var alldata = data1.concat(data2).concat(data3);
res.json("services.ejs", {data: alldata});

Adjust accordingly, depending on what you want in the results.

+3
source

Source: https://habr.com/ru/post/1651105/


All Articles