javascript - 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)
谁能帮我这个?
解决方案
我认为您没有正确访问该 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
推荐阅读
- vb.net - VB.net WindowsForm 改变然后 [System.Data.MissingPrimaryKeyException]
- debian - 如何使用 libxml 库安装和构建
- javafx - Javafx如何在另一个场景的imageview中显示从网络摄像头捕获的图像
- angular - 有没有办法以角度获得标准时间
- c++ - 如何在多个项目之间共享一个主要功能/文件?
- node.js - Testing with Mocha and Chai consuming values from previous tests
- assembly - IBM Assembly中END OF MEMBER有什么用
- tensorflow - tf.gather_nd 多次使用真的很慢
- numpy - Numpy:使用二维索引数组从数组中提取行的快速方法
- netlogo - 涉及问号的高级 netlogo 代码的问题