Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJs/Express dealing with missing static files

I have a node App. That is configured to serve static files by: app.use(express.static(path.join(__dirname, '../public'))); And I use some auth middlewares on other routes. The problem comes up when I hit an image that doesn't exist on the server. In this case looks like express is trying to send that request through all of the middlewares that I have for NON-static content. Is there a way to just send 404 for missing static asset, rather than re-trigger all middlewares per missing file?

like image 912
Max Avatar asked Aug 02 '16 00:08

Max


1 Answers

The way that the express.static() middleware works by default is that it looks for the file in the target directory and if it is not found, then it passes it on to the next middleware.

But, it has a fallthrough option that if you set it to false, then it will immediately 404 any missing file that was supposed to be in the static directory.

From 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.

Example:

app.use("/public", express.static("/static", {fallthrough: false}));
like image 58
jfriend00 Avatar answered Oct 03 '22 20:10

jfriend00