0

I'm a new developer learning how to work with API's and I've run into this error a few times now that keeps crashing Node:

SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/Users/SA/Desktop/pokeApp/app.js:13:34)
    at IncomingMessage.emit (events.js:314:20)
    at IncomingMessage.Readable.read (_stream_readable.js:513:10)
    at flow (_stream_readable.js:986:34)
    at resume_ (_stream_readable.js:967:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

I'm not really sure how to resolve it or what the problem is exactly... my JS code looks like this:

const express = require("express");
const https = require("https");

const app = express();

app.get("/", (req,res) => {
    const url = "https://pokeapi.co/api/v2/pokemon/1/";

    https.get(url, function(response){
        console.log(response.statusCode);

        response.on("data", (data) =>{
            const pokemon = JSON.parse(data);
            console.log(pokemon);
        })
    })

    res.send("server running");
})

app.listen(3000, () => {
    console.log("Port 3000");
})

This is basically the same setup I used for a weatherAPI and had no issues. I also checked the JSON with JSON lint to see if there were any problems and it came back okay.

1 Answer 1

2

You need to wait for the full response to come in - it's a large file, so it may not come in all at once:

https.get(url, function(response){
    let result = '';
    response.on("data", (data) =>{
        result += data;
    });
    response.on('end', () => {
        const pokemon = JSON.parse(result);
        console.log(pokemon);
    });
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! This worked. Just a question, why did adding the data in the first response.on to an empty string allow me to parse the JSON when the response "ends"? I had tried the JSON.stringify() method but it didn't work the same way.
The data event fires multiple times, not just once, since the payload is large, so by concatenating all the data together, it can then be JSON.parsed at the end
great! that makes a lot more sense now.

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.