JSON输入意外结束

yk9xbfzb  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(170)

我试图从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);
                });
            }
            
       
    });
});
mzmfm0qo

mzmfm0qo1#

请注意,每次数据块到达时都会触发response.on("data")事件,每个请求可能会发生多次(不一定所有数据都同时到达,尤其是对于大负载)。
您应该缓冲数据,并仅在所有数据到达后才解析它:

let dataBuffer = '';
response.on("data", function(data) {
   dataBuffer += data;
});

response.on("end", function() {
   const weatherData = JSON.parse(dataBuffer);
   ...
   ...
});

相关问题