Reputation: 11
i am using openweathermap API. When i try to parse response data to json it gives me an error. i dont know what to do about this can anyone help??
CODE:
const express = require("express");
const https = require("https");
const app = express();
app.get("/", function (req, res) {
const url = "https://api.openweathermap.org/data/2.5/forecast?appid=faa02526fbe231fa9d2dc1aa991a26f2&q=London";
https.get(url, function (response) {
console.log(response.statusCode);
response.on("data", function (data) {
JSON.parse(data);
});
});
res.send("upp and running");
});
app.listen(3000, function () {
console.log("up and running");
});
console output:
up and running 200 undefined:1 SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (E:\webdevel\WeatherProject\app.js:14:18)
at IncomingMessage.emit (events.js:375:28)
at IncomingMessage.Readable.read (internal/streams/readable.js:500:10)
at flow (internal/streams/readable.js:982:34)
at resume_ (internal/streams/readable.js:963:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
[nodemon] app crashed - waiting for file changes before starting...
Upvotes: 1
Views: 315
Reputation: 8718
Your problem is that you think that .on("data", handler)
will only be called once with the full reply. That's not how the API works, check the documentation.
Basically, the response body is streamed in. The data
event can be emitted many times, each with a chunk of the body response. Therefore, buffer all the data and wait for the response to finish:
https.get(url, function (response) {
console.log(response.statusCode);
let resultData = '';
response.on('data', data => resultData += data);
response.on('end', () => {
// Now we got the whole response body
JSON.parse(resultData);
});
});
Upvotes: 1