我试图从www.example.com的API获取天气预报数据weatherapi.com但当我解析JSON数据时,它显示json输入意外结束的错误。我还尝试了setTimeout函数,好像它需要时间来获取数据,但没有帮助。
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);
});
}
});
});
1条答案
按热度按时间mzmfm0qo1#
请注意,每次数据块到达时都会触发
response.on("data")
事件,每个请求可能会发生多次(不一定所有数据都同时到达,尤其是对于大负载)。您应该缓冲数据,并仅在所有数据到达后才解析它: