访问 express/REST 中的数组组件



这是我在这个论坛上的第一个问题,所以如果我做错了什么,请善待我。

首先,我将向您展示我的代码:

const express = require('express');
const fs = require('fs');
const app = express();
const port = 8081;
const filename = __dirname + '/jokes.json';
app.use(express.json());
app.get('/jokes/:id', (req, res) => {
fs.readFile(filename,"utf8", (err,data)=>{
if(err){
res.send("Error:"+ err);
}else{
const jokes = JSON.parse(data)[req.params.id];
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(jokes));  
}      
});
});

Jokes.json 文件如下所示:

{
"jokes" : [
{   "id": "1", 
"title": "Zwei Bomben im Keller", 
"text": "Sind zwei Bomben im Keller, sagt die eine zur anderen:"Lass mal hochgehen." "
},
{   "id": "2", 
"title": "Mönche in Asien", 
"text": "Hoch in den japanischen Bergen fragt der Zen-Schüler seinen Meister: „Meister Aikodo, warum denken die Europäer, dass wir alle gleich aussehen? - Antwortet der Meister: „Ich bin nicht Meister Aikodo."
},
{   "id": "3", 
"title": "Privatsphäre", 
"text": "Natürlich müsste ich mal die Fenster putzen, aber Privatsphäre ist auch wichtig."
},
{   "id": "4", 
"title": "Fieser Peter", 
"text": "Susanne: Hallöchen! Peter: Hallöchen! - Susanne: Wie geht es dir! Peter: Wie geht es dir! - Susanne: Äffst du mich nach?! Peter: Äffst du mich nach?! - Susanne: Ich bin hässlich (grinst) Peter: Ja, das stimmt."
},
{   "id": "5", 
"title": "Teewitz", 
"text": "Welchen Tee sollte man besser nicht trinken? - TNT"
}]
}

所以我正在尝试通过笑话数组中的 id 组件访问我的笑话数组中的特定笑话。但问题是,当我启动服务器并在 URL 中输入"http://localhost:8081/jokes/1"时,网站上不会显示任何内容。那么我该怎么做,或者这甚至可能吗?

不要介意笑话数组中的字符串,它们是德语,我是德语,所以我的英语很弱,但我希望你能理解我的问题/问题,我很感激你们能给我的每一个提示/帮助:)

编辑:多亏了你们,问题解决了(见下文:)(

代码中缺少.jokesJSON.parse(data)[req.params.id]undefined,除非你GET /jokes/jokes,因为你的 JSON 文件的顶级对象只有关键的"笑话",其中包含所有的笑话。要解决此问题,请在JSON.parse(data)后添加.jokes

const express = require('express');
const fs = require('fs');
const app = express();
const port = 8081;
const filename = __dirname + '/jokes.json';
app.use(express.json());
app.get('/jokes/:id', (req, res) => {
fs.readFile(filename,"utf8", (err,data)=>{
if(err){
res.send("Error:"+ err);
}else{
const jokes = JSON.parse(data).jokes[req.params.id];
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(jokes));  
}      
});
});

欢迎来到StackOverflow。我不是这里的老手,但我会尽力帮助你。

导入 json 文件,如下所示:const { jokes } = require('...YourPath/jokes.json')

然后让你的app.get()像这样:

app.get('/jokes/:id', (req, res) => {
try {
const { id } = req.params
const filteredJokes = jokes.filter(joke => joke.id === id)
res.json(filteredJokes)
}
catch(err) {
console.log(err)
}
}

问题是您尝试访问不存在的对象属性,因此它返回undefined.方括号[..]允许我们按名称(键(访问对象属性 - 请参阅 属性访问器。在您的示例中(http://localhost:8081/jokes/1(,req.params.id的值(实际上是一个字符串(用于访问名为"1"的属性。

例如:

let data = '{ "1": ["some", "property"] }'
// this 
let jokes = JSON.parse(data)[req.params.id];
// would be the same as
jokes = JSON.parse(data)["1"];
console.log(jokes)
// Output: 
// ["some", "property"]

但是,在您的情况下,JSON.parse(data)返回一个具有唯一属性jokes的对象,这是包含笑话的实际数组。您可以使用.jokes['jokes'].现在要获得对应于req.params.id的笑话,您可以迭代数组并检查每个数组的id属性。

例如:

// parse the contents of 'jokes.json' (data) to an object
const jokes_obj = JSON.parse(data);
// get the `jokes` property (the array)
const jokes_arr = jokes_obj.jokes;

// search for the item whose id corresponds to req.params.id
jokes_arr.forEach(element => {
if(element.id == req.params.id) {
res.writeHead(200, {"Content-Type": "application/json"});
return res.end(JSON.stringify(element));
}
});
// return error message in case no joke matches the ID
return res.end('{ "msg": "ID nor found" }');