nodeJs/Express 处理丢失的静态文件

nodeJs/Express dealing with missing static files

我有一个节点应用程序。配置为通过以下方式提供静态文件: app.use(express.static(path.join(__dirname, '../public'))); 我在其他路线上使用了一些身份验证中间件。当我点击服务器上不存在的图像时,问题就出现了。在这种情况下,express 似乎正在尝试通过我拥有的用于非静态内容的所有中间件发送该请求。 有没有办法只发送 404 来表示丢失的静态资产,而不是针对每个丢失的文件重新触发所有中间件?

express.static()中间件的默认工作方式是在目标目录中查找文件,如果没有找到,则将其传递给下一个中间件。

但是,它有一个 fallthrough 选项,如果你将它设置为 false,那么它会立即 404 任何应该在静态目录中的丢失文件。

来自the express.static() doc

fallthrough

When this option is true, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call next() to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke next(err).

Set this option to true so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

Use false if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

示例:

app.use("/public", express.static("/static", {fallthrough: false}));