Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

882
Vistas
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!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda