Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

I am using an API for some information to display on my web page using https.get() in nodejs. But when I try to console log the response by parsing it as JSON this error is shown

SyntaxError: Unexpected end of JSON input at JSON.parse () at IncomingMessage. (C:\Users\Hardik Aggarwal\Desktop\RSC\app.js:17:33) at IncomingMessage.emit (events.js:315:20) at addChunk (_stream_readable.js:295:12) at readableAddChunk (_stream_readable.js:271:9) at IncomingMessage.Readable.push (_stream_readable.js:212:10)
at HTTPParser.parserOnBody (_http_common.js:132:24) at TLSSocket.socketOnData (_http_client.js:469:22) at TLSSocket.emit (events.js:315:20) at addChunk (_stream_readable.js:295:12)

The URL is sending the correct data in JSON format. The only problem is that JSON.parse() is not working on this data. The code is

app.get("/", function(req, res){
    https.get(url, "JSON", function(response){
        response.on("data", function(data){
            const currency=JSON.parse(data);
            console.log(currency);
        })
    })

    res.render("index");
})
like image 877
Hardik Aggarwal Avatar asked Jan 24 '23 23:01

Hardik Aggarwal


1 Answers

When you use "data" event it means you treat response like a stream and it is not guaranteed that it will send all the data in one chunk. So, in "data" event you should collect all the chunks and in "end" event you should try to parse the data. Also, don't forget to check response.statusCode for error. Try this:

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

https.get(url, "JSON", function(response){
    var data;
    response.on("data", function(chunk) {
      if (!data) {
        data = chunk;
      } else {
        data += chunk;
      }
    });

    response.on("end", function() {
        const currency=JSON.parse(data);
        console.log(currency);
        res.render("index");
    });
});
like image 195
slkorolev Avatar answered Feb 07 '23 18:02

slkorolev