'How to solve SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) while fetching JSON data in NodeJs

I am new in Backend development, Since last few days I am trying to get a response from the api and show it on my html page and i am constantly getting this error while parsing JSON . I am using NodeJS with ExpressJS . Any help would be greatly appreciated!

Here is the error : undefined:1 {"pagination":{"limit":100,"offset":0,"count":22,"total":22},"data":[{"flight_date":"2022-05-01","flight_status":"landed","departure":{"airport":"Vadodara","timezone":"Asia/Kolkata","iata":"BDQ","icao":"VABO","terminal":null,"gate":null,"delay":16,"scheduled":"2022-05-01T11:55:00+00:00","estimated":"2022-05-01T11:55:00+00:00","actual":"2022-05-01T12:10:00+00

SyntaxError: Unexpected end of JSON input at JSON.parse () at IncomingMessage. (C:\Users\2kwattz\Desktop\2kaerostack\server.js:31:35) at IncomingMessage.emit (node:events:390:28) at IncomingMessage.Readable.read (node:internal/streams/readable:527:10) at flow (node:internal/streams/readable:1012:34) at resume_ (node:internal/streams/readable:993:3) at processTicksAndRejections (node:internal/process/task_queues:83:21)

Here is the code:

app.post("/airportracker", function (req, res) {

    let apiKey = 'somekey';  
    let airportiata = req.body.airportiata;
    let url = `http://api.aviationstack.com/v1/flights?access_key=${apiKey}&dep_iata=${airportiata}`;
    http.get(url, function (response) {
        response.on('data', function (data) {

            console.log(data);

            let flightData = JSON.parse(data);
            flightData = flightData.stringify();


            console.log(flightData);
            let flightDate = flightData.data[0].flight_date;

            res.send(`${flightDate}`)


        });
    })


})

Here is the form code:

 <form class="airportracker" action="/airportracker" method="POST">

        <label for="airportIata"> Enter Airport IATA </label>
        <input type="text" name="airportiata" id="airportiata">

        <a href="#"> Psst! Don't know your Airport IATA ? Click here ! </a>

        <button class="btn" id="airportTrackerSubmit" type="submit"> Track Flights </button>
    </form>

I would be really grateful if anyone provides me a solution. Thank you so much in advance!



Solution 1:[1]

You assume that the entire response comes with one data event, but this is not guaranteed, that's why you end up with only a first chunk of JSON (with an "unexpected end").

You must be prepared for several data events, followed by a single end event:

var data = "";
response.on('data', function(chunk) {
  data += chunk.toString();
})
.on('end', function() {
  console.log(data);
  /* Rest of your code */
});

(I don't understand where the undefined:1 in your error log comes from, however.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heiko Theißen