【问题标题】:How can I nicely handle an ENOENT?我怎样才能很好地处理 ENOENT?
【发布时间】:2022-02-07 13:07:05
【问题描述】:

我最近开始制作一个 Express 项目。 我这样做是为了如果有人去localhost:3000/games/tictactoe,他们会收到/games/tictactoe/index.html。 (编辑:我希望路由是动态的;如果用户转到/games/foo,它应该向他们发送该目录的index.html。) 我的目录结构是:

multiplayergames
├── games
│   └── tictactoe
│       └── index.html
└── src
    └── server.js

server.js(目前为止)

const express = require("express")
const app = express()
app.get("/games/:game", (req, res) => {
    res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
})
  
app.listen(3000, () => {
    console.log(`App is up! (${new Date().toLocaleTimeString()})`)
})

唯一的问题是,如果有人去/games/foo,它会显示Error: ENOENT: no such file or directory, stat 'multiplayergames/games/foo/index.html'。 当用户进入不存在的游戏时,有什么方法可以向用户发送“更好”的响应(HTML 页面)?

[另外,如果我动态提供文件的方式有问题,请告诉我;我很快就把它拼凑起来]

【问题讨论】:

  • 既然localhost:3000/games/tictactoe 是固定的,为什么不用为这个路径写一个路由而不是路径参数/games/:game。此外,当用户尝试访问不存在的路由时,您可以使用 404 错误路由发送自定义错误
  • @JatinMehrotra,我认为这实际上不是由于用户转到不存在的路线而引起的 404;这是因为(例如)/games/foo/index.html 不存在,所以 Express 将服务器错误发送给用户。我希望它发送一个 HTML 文件,而不是发送错误。
  • 但是,对于您的其他声明,我应该提到我不想像您似乎建议的那样对路线进行硬编码。我将其添加到问题中。感谢您的帮助!

标签: node.js express


【解决方案1】:

您可以使用 node fs 检查文件是否存在,并返回游戏或自定义 html 文件。 https://nodejs.org/api/fs.html#fsexistssyncpath

const fs = require('fs')
app.get("/games/:game", (req, res) => {
     if (fs.existsSync('/path/to/game/index.html')) {
       res.sendFile(`${req.params.game}/index.html`, {root: "games/"})
     } else {
       res.sendFile('custom 404 html file');
     }
})

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2018-09-03
    • 2011-02-21
    • 2023-03-18
    • 2018-08-09
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多