4

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

1 Answer 1

8

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");
    });
});
Sign up to request clarification or add additional context in comments.

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.