【问题标题】:JSON data not definedJSON 数据未定义
【发布时间】:2021-05-14 08:36:16
【问题描述】:

我尝试制作一个食谱应用程序并使用节点编写了这段代码:

const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");

const app = express();
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
  const numberOfRecipes = req.body.totalRecipes;
  const apiKey = "apiKey...";

  const url = "https://api.spoonacular.com/recipes/random?apiKey=" + apiKey + "&number=" + numberOfRecipes;

  https.get(url, function(response) {
    response.on("data", function(data) {
      const recipeData = JSON.parse(data);
      // console.log(recipeData);
      // console.log(data);
      const title = recipes[0].title;
      res.write("<h1>The title of the recipe is " + title + ".</h1>");
      res.send();
    })
  });
});

app.listen(3000, function() {
  console.log("The server started at port 3000");
});

但是终端说

C:\Users\ArunBohra\Desktop\food-recipes\app.js:23 const recipeData = JSON.parse(data); ^

ReferenceError: 数据未定义 在客户端请求。 (C:\Users\ArunBohra\Desktop\food-recipes\app.js:23:41)

谁能帮我解决这个问题?

【问题讨论】:

  • 一旦第一个data 事件触发,您不能期望解析整个响应。在the documentation 中有一个如何使用它来获取 JSON 的示例,但您最好使用具有更友好 API 的 axios 或 node-fetch 之类的东西。
  • @Quentin 确实如此,但它没有解释为什么 data 未定义。它应该是响应的一部分。
  • @Barmar — 我希望如此,但我尽量避免直接使用该模块。我猜测它可能会被触发,因为标题已经到达但身体没有。
  • @Quentin 文档中的示例代码没有对此进行任何检查。
  • 请检查API返回的状态码。看起来它没有返回 200 状态代码,因此数据可能未定义。

标签: javascript node.js express


【解决方案1】:

我认为您没有正确访问该 API 内容。试试这个:

axios.get('https://api.github.com/users/mapbox')
.then((response) => {

  console.log(response.data);
  console.log(response.status);
  console.log(response.statusText);
  console.log(response.headers);
  console.log(response.config);

});

找到一个流行的第三方库,如 Axios 或其他库,并使用它来进行 API 调用。然后做控制台日志,你会 参考这个How do I use axios within ExpressJS? 还有这个ReferenceError: request is not defined

【讨论】:

  • 我也更喜欢 Axios
  • 这可能是一个很好的建议,但它不能回答为什么他们会收到undefined 的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2016-06-23
  • 1970-01-01
相关资源
最近更新 更多