1

My code is this and I am trying to include COVID 19 API from https://api.covid19api.com/ but when I am trying to parse the data it is showing error without parsing it is showing output in hex.

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));

https = require("https");

app.get("/", function (req, res) {
  url = "https://api.covid19api.com/summary";

  https.get(url, function (response) {
    response.on("data", function (data) {
      console.log(JSON.parse(data));
    });
  });
});

app.listen(3000, function () {
  console.log("server is running ");
});
Mario
  • 4,784
  • 3
  • 34
  • 50

1 Answers1

0

It is returning data in chunks. You have to assemble the data first.

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
    extended: true
}));

https = require("https");



app.get("/", function (req, res) {

    url = 'https://api.covid19api.com/summary';

    const request = https.request(url, function (response) {
        let data = '';

        response.on('data', (chunk) => {
            data += chunk;
        });

        response.on('end', () => {
            const body = JSON.parse(data)
            console.log(body);
        });
    });

    request.on('error', (error) => {
        console.log('An error', error);
    })
    request.end();
});



app.listen(3000, function () {
    console.log("server is running ")
});

By the way, I do recommend using popular npm packages like request (although it seems like it's deprecated). It will make your code a whole lot efficient

arif08
  • 746
  • 7
  • 15