undefined:尝试访问Node.js中解析的JSON值时出现1个错误



我正在尝试制作一个非常基本的新闻web应用程序来学习如何使用API。我使用的API是https://newsapi.org/。

这是我尝试console.log的JSON对象;未定义:1";我收到的错误消息。

这是我的代码:

const express = require("express");
const https = require("https");
const app = express();
app.get("/", function(req, res) {
res.send("Sample text");
const url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=_______________________';
https.get(url, function(response) {
response.on("data", function(data) {
const newsData = JSON.parse(data);
const results = newsData.totalResults;
console.log(results);
});
});
});
app.listen("3000", function(req, res) {
console.log("Server is running on port 3000");
});

我取出了我的API密钥,这样StackOverflow上的人就不能在新闻API上访问我的帐户,但API密钥在我的代码中如上面的链接所示,我想console.log;totalResults";JSON对象中的键值对;38〃;出现在控制台中,但我却收到了";未定义:1">

我该如何更改我的代码,这样我就不会得到";未定义:1";错误,并且我可以显示任何JSON值?

您很可能会得到分块的响应。当接收到块时,会触发data事件,但需要使用单独的end事件来处理获取最后一个数据。

data事件处理程序不应将data视为整个响应,而应将data附加到字符串中。然后您应该添加一个end处理程序来尝试执行JSON.parse

这里的NodeJS文档中有一个很好的例子来处理您的用例。


顺便说一句,您可能想研究一下使用request库,它简化了这个过程。我之所以使用它,是因为我不喜欢在普通的Node请求API中打乱这样的事件处理程序。

最新更新