1

I am building a news/blog website which gets the data from an external api and displays it to the webpage.So far I have managed to render data from one api but I also have a sport section in my webpage which requires me to get data from another such api but i dont know how i can do that without node throwing me an error. Below is my NODE.JS code-

//jshint esversion: 6

const express = require('express');
const https = require('https');
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
const port = 3000;


app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));


app.get('/', (req, res) => {
const sporturl ="https://timesofindia.indiatimes.com/feeds/newsfeed/33187923.cms? 
feedtype=sjson";
const newsurl = "https://timesofindia.indiatimes.com/feeds/newsdefaultfeeds.cms? 
feedtype=sjson#";
https.get(newsurl, function(response){
    var data;
response.on("data", function(chunk) {
    if (!data) {
        data = chunk;
    } else {
        data += chunk;
    }
});

response.on("end", function() {
    const fulldata = JSON.parse(data);
            let mainHeader = fulldata.NewsItem[0].HeadLine;
            let mainheaderurl = fulldata.NewsItem[0].WebURL;
            let mainCaption = fulldata.NewsItem[0].Caption;
            let mainUrl = fulldata.NewsItem[0].Image.Photo;
            let featured = fulldata.NewsItem[1].HeadLine;
            let featuredlink = fulldata.NewsItem[1].WebURL;
            let featuredimg = fulldata.NewsItem[1].Image.Photo;


    res.render("index",{
                mainHeader: mainHeader,
                headerUrl: mainheaderurl,
                mainCaption: mainCaption,
                imgUrl: mainUrl,
                featured:featured,
                featuredlink:featuredlink,
                featuredimg:featuredimg,
            });
     });

     });
  
     });

     app.listen(port, () => {
     console.log(`server started on port 3000`);
     });
    // api key: ff827a803d4540f5814864d207fd23b5
    // const mainHeadingUrl = "https://newsapi.org/v2/everything?q=tesla&from=2021- 
    05-26&sortBy=publishedAt&apiKey=ff827a803d4540f5814864d207fd23b5";

2 Answers2

0

I would use the Fetch API (for nodeJS you could utilise node-fetch), async/await, and Promise.all to gather the data.

Push some API calls into an array. They will return as promises (a promise that data will (or will not) return). Promise.all waits until all those promises have resolved, and outputs the data as an array that you can then iterate over.

function mockApi(n) {
  return new Promise((res, rej) => {
    setTimeout(() => res(n), 2000);
  });
}

// Here you would bundle up your fetch calls
// eg:  fetch(url)
// I'm using mockApi as a convenience
const fetchCalls = [mockApi(1), mockApi(2), mockApi(3)];

async function getData() {
  const data = await Promise.all(fetchCalls);
  console.log(data);
}

getData();
Andy
  • 61,948
  • 13
  • 68
  • 95
0

This is answered here.

nodejs - How to promisify http.request? reject got called two times

You can then use the method described there and use Promise.all and achieve the desired result

Prakash S
  • 1,695
  • 3
  • 11
  • 20