admin管理员组文章数量:1308422
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
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
Share Improve this question asked Jul 13, 2017 at 9:32 VasiVasi 1,2271 gold badge10 silver badges18 bronze badges1 Answer
Reset to default 10Method 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
本文标签: javascriptCan I ignore few static files in express staticStack Overflow
版权声明:本文标题:javascript - Can I ignore few static files in express static? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741861638a2401657.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论