原理详见网络http协议中的缓存

express中已经帮我门默认开启了缓存

我们只需要做一些配置就好,常用配置如下

Property Description Type Default
dotfiles Determines how dotfiles (files or directories that begin with a dot “.”) are treated.

See dotfiles
below. | String | “ignore” | | etag | Enable or disable etag generation

NOTE: express.static always sends weak ETags. | Boolean | true | | extensions | Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: [‘html’, ‘htm’]. | Mixed | false | | fallthrough | Let client errors fall-through as unhandled requests, otherwise forward a client error.

See fallthrough
below. | Boolean | true | | immutable | Enable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed. | Boolean | false | | index | Sends the specified directory index file. Set to false to disable directory indexing. | Mixed | “index.html” | | lastModified | Set the Last-Modified header to the last modified date of the file on the OS. | Boolean | true | | maxAge | Set the max-age property of the Cache-Control header in milliseconds or a string in ms format
. | Number | 0 | | redirect | Redirect to trailing “/” when the pathname is a directory. | Boolean | true | | setHeaders | Function for setting HTTP headers to serve with the file.

See setHeaders
below. | Function | |

更加详细的配置见官网 https://www.expressjs.com.cn/4x/api.html#express.static

express中设置过期时间

  1. app.use(express.static(rootPath, {
  2. index: 'index.html', //默认访问页面,默认值为index.html,可修改
  3. // maxAge: 3600 * 1000,
  4. setHeaders: (res, path) => {
  5. if (!path.endsWith('.html')) {
  6. res.setHeader('Cache-Control', `max-age=${4800 * 10}`)
  7. }
  8. }
  9. }));
  1. 直接设置过期时间,是对所有的请求资源都设置为3600*1000的过期
  2. setHeaders: 不对静态html文件进行缓存,因为静态html文件在我们的项目中(vue,react),一般动态引入的打包后的css,js文件,所以静态html文件,不需要缓存