I am trying to get weather forecast data from API of weatherapi.com but when I parsed the JSON data it show error that unexpected end of json input. I also tried setTimeout function as if it takes times to fetching data but not helpful.
const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.post("/weather-data",function(req, res){
var city_name = req.body.city_name;
city_name = city_name.toUpperCase();
const key = "4b6f380fa80745beb2c174529222912";
const days = 1;
url = "https://api.weatherapi.com/v1/forecast.json?key="+key+"&q="+city_name;
https.get(url,(response)=>{
console.log(response.statusCode);
const status = response.statusCode;
if(status == 200){
response.on("data",function(data){
const WeatherData = JSON.parse(data);
const region = WeatherData.location.region;
const country = WeatherData.location.country;
console.log("region is "+region+" and country is "+country);
});
}
});
});
Note that response.on("data")
event is triggered every time a chunk of data arrives and it can happen multiple times per request (not necessarily all data arrive simultaneously, especially for large payloads).
You should buffer the data and parse it only after all data arrived:
let dataBuffer = '';
response.on("data", function(data) {
dataBuffer += data;
});
response.on("end", function() {
const weatherData = JSON.parse(dataBuffer);
...
...
});