简体   繁体   中英

JSON.parse() Returning Unexpected end of input

[`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"));

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

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

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);
            
        })
    })
})
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....

Listen for 'end ' the problem will be resolved

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM