首页 > 解决方案 > JSON 数据未定义

问题描述

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

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:数据未在 ClientRequest 中定义。(C:\Users\ArunBohra\Desktop\food-recipes\app.js:23:41)

谁能帮我这个?

标签: javascriptnode.jsexpress

解决方案


我认为您没有正确访问该 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 调用。然后做控制台日志,你会参考这个我如何在 ExpressJS 中使用 axios? 而这个ReferenceError: request is not defined


推荐阅读