How to configure caching of headers on subdirectories in express

When using express with node.js, you can manage the caching headers for public resources as follows:

app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); 

This sets everything under a shared folder, which should be statically accessible with a 1 year cache timeout. But what if I want to set a different timeout value for other files in the open? Say I have images under the signs public / images / icons that I want to be of less value than 1 year? I tried adding a second static call as follows:

 app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); app.use(express.static(path.join(__dirname, 'public/images/icons'), { maxAge: 12345 })); 

but it didn’t work. This seems to just ignore the second statement. Thoughts?

+4
source share
3 answers

Express tests the middleware in order, so if you first put the most specific call to express.static, then it should work, i.e.

 app.use(express.static(path.join(__dirname, 'public/images/icons'), { maxAge: 12345 })); app.use(express.static(path.join(__dirname, 'public/images'), { maxAge: 1234567 })); app.use(express.static(path.join(__dirname, 'public/else'), { maxAge: 9874567 })); app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); 

and etc.

Edit:

This will not support the path, so I would do

 function static(dirname, age) { return express.static(path.join(__dirname, dirname), { maxAge: age }); } 

and then call

 app.use('/public/images/icons', static('public/images/icons', 12345)); app.use('/public/images/', static('public/images', 1234567); 

and etc.

The reason for this is because my previous solutions mount all the static files in the root, whereas this solution mounts every directory in this file path with the correct maxAge

+4
source

The source code of the static middleware shows that it intercepts everything that looks like a file path from part of the URL path, sets the file from the configured root directory, and serves it if it exists.

There is no way to change maxAge parameters using vanilla middleware.

I suggest you create your own middleware (just a function) and create the appropriate amount of static middleware (for each directory) and redirect the req, res, next parameters to the correct one

+1
source

You need to set each folder inside public to its own path, since it will be a server. That is, without public .

 app.use('/css', express.static(__dirname + '/public/css', { maxAge: '1h'})); app.use('/img', express.static(__dirname + '/public/img', { maxAge: '1h'})); app.use('/fonts', express.static(__dirname + '/public/fonts', { maxAge: '1h'})); app.use(express.static(path.join(__dirname, 'public'))); 
0
source

Source: https://habr.com/ru/post/1469561/


All Articles