簡體   English   中英

解析openweathermap api響應數據node.js時JSON輸入意外結束

[英]Unexpected end of JSON input while parsing openweathermap api response data node.js

我正在使用 openweathermap API。 當我嘗試將響應數據解析為 json 時,它給了我一個錯誤。 我不知道該怎么辦,有人可以幫忙嗎??

代碼:

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"); 
});

控制台輸出:

啟動並運行 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] 應用程序崩潰 - 在開始之前等待文件更改...

您的問題是您認為.on("data", handler)只會在完整回復時被調用一次。 這不是 API 的工作方式,請查看文檔。

基本上,響應正文是流式傳輸的。 data事件可以發出多次,每次都有一個正文響應塊。 因此,緩沖所有數據並等待響應完成:

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);
    });
}); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM