gpt4 book ai didi

node.js - nodeJs/Express 处理丢失的静态文件

转载 作者:搜寻专家 更新时间:2023-10-31 23:34:48 24 4
gpt4 key购买 nike

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

关于node.js - nodeJs/Express 处理丢失的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38709864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com