处理静态资源:自带缓存 重定向到304缓存
简单代码:
const Koa = require("koa");
const static = require('koa-static');
let server = new Koa();
server.listen(8000);
server.use(static('./static', {
maxage: 60*86400*1000, // 60天
index: "index.html"
}));
static中可以传两个参数:
第一个参数:指定目录
第二个参数:JSON对象:
- maxage 周期 在这个周期内都向浏览器说没有更新资源
- index 单客户端不明确要什么,返回index.html文件
-
谷歌浏览器中的Disable cache勾上表示强制不适用缓存。
当第二次访问http://localhost:8000/1.txt, disk catch表示用的缓存。
给不同的内容设置不同的缓存,static结合router使用。
const Koa = require("koa");
const Router = require("koa-router");
const static = require('koa-static');
let server = new Koa();
server.listen(8000);
let router=new Router();
router.all(/\.(jpg|png|gif)$/i, static('./static', {
maxage: 60*86400*1000
}))
router.all(/\.css$/i, static('./static', {
maxage: 7*86400*1000
}))
router.all(/\.js$/i, static('./static', {
maxage: 1*86400*1000
}))
router.all(/\.html$/i, static('./static', {
maxage: 1*86400*1000
}))
router.all('*', static('./static', {
maxage: 7*86400*1000
}))
server.use(router.routes());