SaintArnelly
SaintArnelly

Reputation: 3

SyntaxError: Unexpected end of JSON input (Node.js)

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.

Upvotes: 0

Views: 3719

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

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

Upvotes: 2

Related Questions