【问题标题】:undefined:1 error when trying to access parsed JSON value in Node.js尝试访问 Node.js 中解析的 JSON 值时出现 undefined:1 错误
【发布时间】:2020-12-14 10:22:39
【问题描述】:

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

This is the JSON object that I'm trying to console.log and the "undefined:1" error message that I'm receiving.

这是我的代码:

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 密钥在我的代码中。 如上面的链接所示,我想控制台记录 JSON 对象中的“totalResults”键值对,以便控制台中出现“38”,但我收到的是“undefined:1”。

如何更改我的代码,以免出现“undefined:1”错误并且可以显示任何 JSON 值?

【问题讨论】:

  • 您能否在解析数据之前直接控制台记录数据,看看您是否得到任何响应
  • 我得到一些看起来像十六进制的东西:

标签: javascript node.js json express https


【解决方案1】:

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

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

a good example in the NodeJS docs here 可以解决您的用例。


顺便说一句,您可能想考虑使用the request library,它可以简化此过程。我使用它是因为我不喜欢在 vanilla Node 请求 API 中像这样搞乱事件处理程序。

【讨论】:

  • 感谢您的回复。澄清一下:我了解网络以块/数据包的形式发送数据。您是说事件处理程序 response.on("data", ___) 在接收到第一个块然后停止时被调用?因此,要解决这个问题,我应该将块添加到字符串中,然后使用 response.on("end", ___) 来解析 JSON?
  • 我遵循了 NodeJS 文档,它解决了我的问题!谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2021-12-28
  • 2014-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多