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

Only load the value in ref when it is specifically requested in Vue

Within my Vue project, I am utilizing a ref variable that stores data retrieved from a database. This reference is contained within Pinia's setup store for easy access. The objective is to load the data only when requested by the user and then always ...

Transferring information from JavaScript to PHP

I am trying to send both the data and text that are within a single DIV tag using JavaScript into PHP values. However, I am encountering an issue with the following code: <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq ...

Reasons Behind Slow Unmounting of React Components

In my current project, I have implemented a component that wraps multiple ReactList components. The ReactList component features infinite scrolling, meaning it only loads what is currently in the viewport. There are two modes available - simple and uniform ...

Click on the button to reveal the hidden content within the div, and then smoothly scroll down to view

I have a footer div that is present at the bottom of every page on our site. I've added a button to expand this div, but I'm looking for a way to automatically scroll the page down so that the user can view the expanded content without manually s ...

React DataGrid fails to refresh when state changes

Currently, I am in the process of developing a link tree using the Datagrid Component provided by MaterialUI. While data can be successfully displayed, I encounter an issue when attempting to add a new entry. The problem lies in the fact that despite cha ...

Utilize mongoose-delete to bring back items that have been marked for deletion but are still

Whenever I remove an item from my list, it switches the properties of the data to true, marking it as deleted and moves it to the trash. However, when I try to restore the item from the trash, the deleted properties are no longer available and the data rea ...

Issue with triggering ReactJS onClick function accurately

For the function to work correctly, I had to add e.preventDefault(). However, my goal is for it to redirect the user to '/' after submitting the form. Below is the function that I am attempting to trigger: onAddPoints = (e) => { e.prevent ...

Turning list outcomes into objects

Upon receiving a response from my server, it appears like the following: [ { "_id": "559d443abae4f14958f6a854", "owner": "559d4323bae4f14958f6a852", "__v": 0, "updated_at": "2015-07-08T15:39:38.370Z", "expiratio ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Handling JSON Deserialization Error in C# with jQuery and ASMX

Trying to perform an AJAX POST request to a C# ASMX web method, but encountering issues with JSON data deserialization. Despite following the correct steps, I keep getting the error message... {"Message":"Cannot convert object of type \u0027System.St ...

Is Jquery getting imported correctly, but AJAX is failing to work?

I am currently working on a Chrome extension that automatically logs in to the wifi network. I have implemented AJAX for the post request, but when I inspect the network activity of the popup, I do not see any POST requests being sent. Instead, it only sho ...

A more efficient method for passing a function as an argument using the keyword "this"

When it comes to passing a function as an argument that uses the this keyword, is there a preferred method or correct way to do so? An example would be helpful in understanding this concept better: For instance, if I want to fade out an object and then r ...

How can I direct to an HTML file using Vue 3 router?

I'm working with Vue 3 and I have a unique challenge. I want to connect a static landing page HTML file to the home route / in my Vue application, but this HTML file is completely separate from the original index.html used by Vue 3. This standalone HT ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

How to harness the power of loops in JavaScript

Having trouble getting this code to repeat a CSS transition properly. for (var i=0 ; i<4 ; i++){ setTimeout(function() { $('#top-left').css('margin', '45px 0 0 45px'); $('#top-mid' ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Replace !important with JavaScript/jQuery when using animate()

I need to animate the background-position-x, but there is a background-position: 0 0 !important; set in the css that cannot be removed. Is it possible to work around this using JavaScript? My jQuery code is functioning as intended, but it is being overridd ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

Error: The function setOpenModal is not defined

I'm currently working on creating a login modal popup that will appear when a button inside a navbar is clicked. However, I'm encountering the following error: TypeError: setOpenModal is not a function Despite going through various discussions ...