Vas*_*asi 1 javascript node.js express
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');
})
Run Code Online (Sandbox Code Playgroud)
在我的代码中为服务静态文件表达了静态。我想为几个文件而不是所有文件添加maxage标头。
我可以为几个文件添加maxage标头吗?
- app
- js
- app.js
- css
- app.css
- index.html
Run Code Online (Sandbox Code Playgroud)
这是我的应用程序的静态路径。我想将maxage标头添加到所有文件而不是index.html
方法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')));
Run Code Online (Sandbox Code Playgroud)
方法2
您保留您的js / css / images / etc。在不同的子文件夹中。例如,也许您将所有内容都保留在public /中,但html文件不在public / templates /中。在这种情况下,您可以按路径拆分它:
var serveStatic = require('serve-static')
app.use('/templates', serveStatic(__dirname + '/public/templates'), { maxAge: 0 })
app.use(serveStatic(__dirname + '/public'), { maxAge: '1y' })
Run Code Online (Sandbox Code Playgroud)
方法3
您的文件都是相互混合的,并且要将0 max age应用于所有文本/ html文件。在这种情况下,您需要添加标题设置过滤器:
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')
}
}
}))
Run Code Online (Sandbox Code Playgroud)
方法2和3是从github复制的
| 归档时间: |
|
| 查看次数: |
1088 次 |
| 最近记录: |