You can pass a maxAge
option to both favicon and static middleware :
app.use(express.favicon(__dirname + '/public/favicon.ico', { maxAge: 2592000000 }));
Sources :
سؤال
In Express I add expires headers to my static files like this
app.use(function (req, res, next) {
// static folder: css
if (req.url.indexOf('/css/') === 0) {
res.setHeader('Cache-Control', 'public, max-age=345600'); // 4 days
res.setHeader('Expires', new Date(Date.now() + 345600000).toUTCString());
}
});
app.use(express.static(root + '/app'));
What I cannot do is catch the favicon.ico request like this.
Is there a way to add expires header to favicon in Node/Express?
What makes the favicon.ico request so different compared to other static files?
Thx!
المحلول
You can pass a maxAge
option to both favicon and static middleware :
app.use(express.favicon(__dirname + '/public/favicon.ico', { maxAge: 2592000000 }));
Sources :
نصائح أخرى
I think using that instead is more SEO friendly
app.use(express.static(__dirname + '/public', {
maxAge: 86400000,
setHeaders: function(res, path) {
res.setHeader("Expires", new Date(Date.now() + 2592000000*30).toUTCString());
}
}))
The answer here is correct but a little dated as express no longer supports this middleware, so the easy fix is to use this package.
https://github.com/expressjs/serve-favicon
var connect = require('connect')
var favicon = require('serve-favicon')
var path = require('path')
var app = connect()
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
// Add your middleware here, etc.
app.listen(3000)
Code is right from the link above...