0

I am fetching data from movieDB API in nodeJS using http.request method. While it works most of times, I am getting error if I reload the page(make API call) more than 10 or 15 times . Following is my code here -

router.get("/", (req, res, next) => {
  let request = http.request(nowPlayingUrl, (response) => {
    // response is a readable stream
    let chunk = [];
    console.log(response.headers);
    response.on("data", (data) => {
      chunk.push(data);
    });
    response.on("end", () => {
      console.log("all data received");
      console.log(JSON.parse(chunk));
    });
  });
  request.end();
  res.render("index.ejs");
});

and heres the error -

SyntaxError: Unexpected token , in JSON at position 10855
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous>

there is also partial stringified data before app crashes with above mentioned error.

converting the chunk array to string and then parsing it to JSON doesnt produces any error -

`let d = JSON.stringify(chunk);
 console.log(JSON.parse(d));`
Baba
  • 11
  • 3

1 Answers1

1

You use JSON.parse on an array of strings, which tries to parse the comma-separated list of these strings. That is probably no valid JSON. Use JSON.parse on a string instead:

let chunk = "";
response.on("data", (data) => {
  chunk += data.toString();
});
response.on("end", () => {
  console.log(JSON.parse(chunk));
});

Of course this assumes that nowPlayingUrl does indeed return valid JSON.

JSON.stringify followed by JSON.parse just re-produces the array, but that's probably not what you want.

Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31