简体   繁体   English

解析openweathermap api响应数据node.js时JSON输入意外结束

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

i am using openweathermap API.我正在使用 openweathermap API。 When i try to parse response data to json it gives me an error.当我尝试将响应数据解析为 json 时,它给了我一个错误。 i dont know what to do about this can anyone help??我不知道该怎么办,有人可以帮忙吗??

CODE:代码:

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

console output:控制台输出:

up and running 200 undefined:1 SyntaxError: Unexpected end of JSON input启动并运行 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] app crashed - waiting for file changes before starting... [nodemon] 应用程序崩溃 - 在开始之前等待文件更改...

Your problem is that you think that .on("data", handler) will only be called once with the full reply.您的问题是您认为.on("data", handler)只会在完整回复时被调用一次。 That's not how the API works, check the documentation.这不是 API 的工作方式,请查看文档。

Basically, the response body is streamed in. The data event can be emitted many times, each with a chunk of the body response.基本上,响应正文是流式传输的。 data事件可以发出多次,每次都有一个正文响应块。 Therefore, buffer all the data and wait for the response to finish:因此,缓冲所有数据并等待响应完成:

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