Error: JSON data abruptly terminated (Node.js)

As a beginner developer diving into the world of API's, I've encountered a recurring error in Node.js that seems to be causing crashes:

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 unsure how to troubleshoot this issue or pinpoint the exact problem. Here is a snippet of my JavaScript code:

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 setup worked flawlessly with a weatherAPI, so I'm puzzled by this hiccup. I even ran the JSON through a lint tool and it came back clean.

Answer №1

Be patient for the full response to arrive - it's a large file, so it may not load all at once:

Make an HTTPS request to the URL and handle the data as it comes in:
https.get(url, function(response){
    let result = '';
    response.on("data", (data) =>{
        result += data;
    });
    response.on('end', () => {
        const pokemon = JSON.parse(result);
        console.log(pokemon);
    });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to showcase a dropdown list within a constantly changing table?

I have a table code snippet that I need help with <fieldset class="tabular"><legend><%= l(:redmine_taskjuggler) %></legend> <%= labelled_fields_for(@issue) do |f| %> <div id="taskjuggler" class="attributes"> <div cl ...

"Enhance the functionality of material-table by incorporating a multi-select feature

My data management has been made easier with Material-Table, but I have encountered a small issue. The code below shows how I currently get a select menu for my data. However, I am looking to have a multiselect menu instead, allowing me to save more than o ...

"Figuring out a way to include a link with each image in a react-s

I am currently working on a project in Gatsby and encountering some issues with the homepage banner. I am using react-slick which seems to be functioning fine, but when I try to add content on top of each image, it causes some problems. Specifically, setti ...

NodeJS making seven successful Ajax requests

I'm delving into the world of JavaScript, NodeJS, and electron with a goal to create a presenter-app for remote control over powerpoint presentations. My setup involves an electron server structured like this: const electron = require('electron ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...

Customize Text Area's Font Based on Selected Option in Dropdown List

I'm currently working on an HTML file that includes a dropdown list and a text area. Here's the code snippet: <select id='ddlViewBy' name='ddlViewBy' onchange='applyfonttotextarea()'> <option value = ' ...

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...

Node.js program closes immediately upon Java startup

I am building a Discord bot that features a Java FXML interface and utilizes a Node.js program to function as an Audio playing bot. However, I am encountering an issue where the process for Node.js closes immediately when opened in Java. The problem arise ...

Can you explain the meaning of this PHP syntax and why is this variable showing NaN?

Looking for question marks on Google can be quite challenging. Can someone explain this process step by step? $page = isset($_POST['page'])?$_POST['page']:"0"; I believe it means to check if $_POST['page'] is set, use that ...

Trouble with executing two asynchronous AJAX calls simultaneously in ASP.NET using jQuery

When developing a web application in asp.net, I encountered an issue with using jQuery Ajax for some pages. The problem arose when making two asynchronous Ajax calls - instead of receiving the results one by one, they both appeared simultaneously after the ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

Updating the content within a div following the submission of a contact form 7

I'm struggling with my contact form. I want the content of my contact form div to change after clicking submit on the form. I've been searching for a solution, but so far, no luck. Here is what I have: Form (div1) with input fields, acceptance c ...

"Exploring the benefits of using nested mapping for res.json() in an Express application

I have been developing an express application (server-side) that offers movie information to users, and I am attempting to send a JSON response in the following format: { "title": "Star Trek: First Contact", "year": 1996, ...

When attempting to render mathML in a canvas on Safari, the image load callback does not properly trigger, resulting in

I am currently working on rendering mathML into an HTML5 canvas. One suggestion I received was to embed the mathML as an SVG foreign object, render it into an image, and then display the image within the canvas. However, this method works fine in Firefox ...

The error message "AttributeError: module 'pandas' does not have the attribute 'DataFrame'" indicates that the code is correct

Just ran this code snippet for testing import pandas as pd userInput ={ 'Principal':1000, 'terms':15, 'age':33, 'Gender':1, 'weekend':1, 'Bechalor':0, 'High Sch ...

Error: authentication failed during npm installation due to an incorrect URL

After executing npm install @types/js-cookie@^2.2.0, an error occurred: npm install @types/js-cookie@^2.2.0 npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="https://pkgsprodsu3weu.app.pkgs.visualstudio.com/" npm ERR! A com ...

Error 404: Page not found. Sorry, we couldn't locate the Node JS and Express resource

I have been trying to access the routes /api and /api/superheroes, but I keep encountering an error message whenever I try. Not Found 404 NotFoundError: Not Found at C:\Users\mikae\Desktop\Project\node-express-swig-mongo\a ...

Checking if an array exists after parsing JSON using jQuery

I am working on a solution to automatically submit form fields after triggering the onchange event. After making some changes, the JSON response I receive appears in this format: { "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } ...

Sending a $.ajax post request transforming into a get

Struggling to understand the behavior of my jquery ajax request, I've hit a roadblock. function newContact() { $.ajax({ type: 'POST', contentType: 'application/json', // url: ...