【发布时间】: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