JSON 输入意外结束

问题描述 投票:0回答:2

我正在尝试从weatherapi.com的API获取天气预报数据,但是当我解析JSON数据时,它显示错误,即json输入意外结束。我还尝试了 setTimeout 函数,好像获取数据需要时间,但没有帮助。

enter image description here

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);
                });
            }
            
       
    });
});
json api express google-api-nodejs-client weather-api
2个回答
0
投票

请注意,每次一大块数据到达时都会触发

response.on("data")
事件,并且每个请求可能会发生多次(不一定所有数据同时到达,尤其是对于大负载)。

您应该缓冲数据并仅在所有数据到达之后解析它:

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

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

0
投票

如果您参与过 MERN 项目,请不要忘记启动后端

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.