1

[`const express = require('express'); const app = express(); const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => { res.send("Server is Running")

https.get(url, (response) => {
    
    response.on("data", (data) => {

        const TimelineData = JSON.parse(data);
        console.log(TimelineData);
        
    })
})

})

app.listen(3000, ()=>console.log("Server is Running 0n 5000"));`]1

const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
    res.send("Server is Running")

    https.get(url, (response) => {
        
        response.on("data", (data) => {

            const TimelineData = JSON.parse(data);
            console.log(TimelineData);
            
        })
    })
})



app.listen(3000, ()=>console.log("Server is Running 0n 5000"));

6
  • Welcome to StackOverflow! To get accurate answers, you should write what is your target and what problem is making you stuck, attach the portion of code interested (whole formatted and not only for certain parts) and also explain what you've tried to solve the issues Commented Jul 29, 2020 at 7:25
  • response.on("data", (data).... is not the whole body response. It can be fired multiple times and you have to concat all chunks together for your full response. "data" is a invalid json string because its sliced into multiple chunks. listen for the "end" event and do your json parsing there. Commented Jul 29, 2020 at 7:52
  • Please provide what the JSON looks like if you want the correct answer. Commented Jun 23, 2021 at 11:55
  • @hackKaTun3s i.sstatic.net/YeqWy.png Commented Aug 8, 2021 at 18:55
  • If you check the console @soumeshkumar the data is not full. Check the end. Commented Aug 8, 2021 at 18:56

6 Answers 6

3

To deliver large data in an effective manner API send data in chunk/stream format. and to receive each chunk it triggers the 'data' event and in your case, it might be possible that API sends data in chunk format. and it will not send you complete data in a single event.

Let's assume the complete response of your API is : { name: 'bella', age: 34, count: 40138 }

And API send it in 2 chunks :

  • Chunk1: { name: 'bella', age: 34, count: 4013
  • Chunk2: 8 }

In that case Json.Parse() on Chunk1 or Chunk2 will not work and threw an exception.

To deal with this problem you need to listen to the 'end' event and capture data from the'data' and parse it in the 'end' event.

Use the below code:

const express = require('express');
const app = express();
const https = require('https');

const url = "https://archive.org/advancedsearch.php?q=subject:google+sheets&output=json";

app.get("/", (req, res) => {
  res.send("Server is Running")

  https.get(url, (response) => {
    var responseData = '';

    response.on("data", (dataChunk) => {
      responseData += dataChunk;

    })

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

  }).on('error', (e) => {
    console.error(e);
  });
})



app.listen(5000, () => console.log("Server is Running 0n 5000"));

Sign up to request clarification or add additional context in comments.

Comments

0

The "data" event can be fired multiple times: https://nodejs.org/api/http.html#http_class_http_clientrequest

You have to listen for the "end" event and concat all chunks from the "data" event togehter for the full body response.

const express = require('express');
const app = express();
const https = require('https');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req, res) => {

    res.send("Server is Running")

    https.get(url, (response) => {

        const chunks = [];

        response.on("data", (data) => {
            chunks.push(data);
        })

        response.on("end", () => {

            let size = chunks.reduce((prev, cur) => {
                return prev + cur.length;
            }, 0);

            let data = Buffer.concat(chunks, size).toString();

            console.log(JSON.parse(data))

        });

    })

})



app.listen(3000, () => console.log("Server is Running 0n 5000"));

Comments

0

why are you using https? replace https with http and run it again.

const express = require('express');
const app = express();
const http = require('http');

const url = "https://api.thevirustracker.com/free-api?countryTimeline=US";

app.get("/", (req ,res) => {
    res.send("Server is Running")

    http.get(url, (response) => {
        
        response.on("data", (data) => {

            const TimelineData = JSON.parse(data);
            console.log(TimelineData);
            
        })
    })
})

Comments

0
const express = require('express')
const app = express()

const port = 3000

app.post('/', (req, res) => { 
  res.send('Hello World!")

})

app.listen(port, () => {
  console.log('server running')

})

When you run the program in nodejs, open the brower and type http://localhost:3000. The output will be....

3 Comments

Hi IjajAhmed Jaman. You are still editing, aren't you? Take this as guidance How to Answer and take the tour at your convenience please.
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
Looks like you had an unexpected end of output. I've edited this for grammar. Could finish the final sentence?
0

Listen for 'end ' the problem will be resolved

Comments

0

Try importing all the dependencies. Importing is better than requiring because you can selectively load only the pieces you need. Also in package.json file add "type":"module" before scripts. The days of const something= require('something') are a thing of the past now because of new ESM modules.

import express from 'express';
import https from 'https';
const app=express();
const port=3000;

In package.json file

"name": "restApiWithNode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",

Read this article for clarity https://formidable.com/blog/2021/node-esm-and-exports/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.