我有以下代码,如果定义了正确的 req.path
,它会返回一些文本。我需要显示 404 未找到。
如果我将它放在有条件的 for 循环中,它会通过使用 break;
返回一堆 not found
,它有点工作。
我的伪代码大致是这样的:如果 Obj 存在则打印它,否则显示 404 页面。
在这种情况下,我应该把 res.send(404)
放在哪里?
app.get('/', (req, res) => {
res.send("Welcome!")
})
app.get('*', (req, res) => {
jsonfile.readFile(file, (err, obj) => {
let pokedex = obj.pokemon
let result = []
let format = req.path.split('/');
let userPath = format[1]
for (var i = 0; i < pokedex.length; i++) {
if (userPath == pokedex[i].name.toLowerCase()) {
result.push(
"<h1>" + pokedex[i].name + "</h1><ul>Weight: " + pokedex[i].weight + "</ul>" );
}
}
res.send(result.join())
})
})
最佳答案
在 res.send(result.join())
之前做:
if(result.length < 1) {
res.send(404);
return;
}
关于javascript - Express:如果 JSON 中不存在对象,如何返回 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968400/