最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I ignore few static files in express static? - Stack Overflow

programmeradmin0浏览0评论
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 badges
Add a ment  | 

1 Answer 1

Reset to default 10

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

发布评论

评论列表(0)

  1. 暂无评论