安装koa-static
npm i koa-static -D
老规矩,直接上代码
const koa = require('koa')
const Router = require('koa-router')
const static = require('koa-static')
let server = new koa();
server.listen(8080)
//引入路由机制
let router = new Router();
router.get('/login', async ctx => {
})
//给server绑定路由
server.use(router.routes())
//读取文件 分批添加缓存时间 不同文件设置不同的缓存时间
let staticRouter = new Router();
staticRouter.all(/(\.jpg|\.png|\.gif)$/i, static('./static', {
maxage: 60 * 86400 * 1000
}))
staticRouter.all(/(\.css)$/i, static('./static', {
maxage: 20 * 86400 * 1000
}))
staticRouter.all(/(\.html|\.htm|\.shtml)$/i, static('./static', {
maxage: 20 * 86400 * 1000
}))
//*代表之外的文件
staticRouter.all('*', static('./static', {
maxage: 30 * 86400 * 1000
}))
server.use(staticRouter.routes())
觉得代码太多的,可以把staticRouter 在封装一层