const express = require('express');
const app = express();
app.use('/app', express.static(path.resolve(__dirname, './app'), {
maxage: '600s'
}))
app.listen(9292, function(err){
if (err) console.log(err);
console.log('listening at http:localhost:9292/app');
})
In my code have express static for serve static files. I want to add maxage header for few files not to all files.
Can I add maxage header for few files?
- app
- js
- app.js
- css
- app.css
- index.html
This is my app's static path. I want to add maxage header to all files instead of index.html
Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.
You need express. static so your server can serve files that aren't being generated on the fly. It handles all the file loading and prevents path traversal attacks.
To serve static files such as images, CSS files, and JavaScript files, use the express.
Static files are files that don't change when your application is running. These files do a lot to improve your application, but they aren't dynamically generated by your Python web server. In a typical web application, your most common static files will be the following types: Cascading Style Sheets, CSS.
Method 1
app.use(function (req, res, next) {
console.log(req.url);
if (req.url !== '/app/index.html') {
res.header('Cache-Control', 'public, max-age=600s')
}
next();
});
app.use('/app', express.static(path.resolve(__dirname, './app')));
Method 2
You keep your js/css/images/etc. in different sub folders. For example, perhaps you keep everything in public/, except your html files are in public/templates/. In this case, you can split it by path:
var serveStatic = require('serve-static')
app.use('/templates', serveStatic(__dirname + '/public/templates'), { maxAge: 0 })
app.use(serveStatic(__dirname + '/public'), { maxAge: '1y' })
Method 3
Your files are all inter-mingled and you want to apply the 0 max age to all files that are text/html. In this case, you need to add a header setting filter:
var mime = require('mime-types')
var serveStatic = require('serve-static')
app.use(serveStatic(__dirname + '/public', {
maxAge: '1y',
setHeaders: function (res, path) {
if (mime.lookup(path) === 'text/html') {
res.setHeader('Cache-Control', 'public, max-age=0')
}
}
}))
method 2 and 3 are copied from github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With