javascript - Express:如果 JSON 中不存在对象,如何返回 404?

标签 javascript json node.js express

我有以下代码,如果定义了正确的 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/

相关文章:

javascript - 以模式显示来自表单提交(Mailchimp)的响应

javascript - 为什么声明类型 <any> 可以解决未知方法的错误? ( typescript )

c# - 使用 HttpClient 异步方法返回格式错误的字符串

node.js - 解析错误: Expected another key-value pair

javascript - JQuery 附加不加载切换按钮的 css

javascript - 现在的浏览器真的不隐藏 javascript 吗?

javascript - 使用 CodeIgniter 中的复选框生成特定行的 Excel 报告

android - 使用 Moshi 处理损坏的服务器响应

javascript - != 在 jade/pug 中做什么?

javascript - 动态更新 'nested' javascript对象