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));`