直接上代码,代码胜过一切
main.js
const Koa = require("koa");
const cacheRouter = require("./cacheRouter");
const cors = require("koa2-cors");
const app = new Koa();
app.use(cors()).use(cacheRouter);
app.listen(8888);
cacheRouter.js
const Router = require("koa-router");
const Mock = require("mockjs");
const fs = require("fs");
const router = new Router();
const cacheRouter = new Router();
router.get("/cache", ctx => {
ctx.body = "测试缓存";
});
cacheRouter.get("/expires", async ctx => {
ctx.set("Expires", new Date(Date.now() + 10000).toUTCString());
ctx.body = await Mock.mock({
title: "强缓存:expires",
"list|5-10": [
{
name: "@cname(2,3)",
"id|+1": 1,
address: "@county(true)"
}
]
});
});
cacheRouter.get("/cacheControl", async ctx => {
ctx.set("cache-control", "max-age=10");
ctx.body = await Mock.mock({
title: "强缓存:cache-control",
"list|5-10": [
{
name: "@cname(2,3)",
"id|+1": 1,
address: "@county(true)"
}
]
});
});
cacheRouter.get("/modified", ctx => {
let pathname = `${__dirname}/string.txt`;
let stat = fs.statSync(pathname);
const data = fs.readFileSync(pathname).toString();
if (ctx.header["if-modified-since"] === stat.mtime.toUTCString()) {
ctx.status = 304;
} else {
ctx.set("Last-Modified", stat.mtime.toUTCString());
}
ctx.body = data;
});
cacheRouter.get("/eTag", ctx => {
let pathname = `${__dirname}/string.txt`;
let stat = fs.statSync(pathname);
const data = fs.readFileSync(pathname).toString();
let Etag = `${data.length.toString(16)}${stat.mtime.toString(16)}`;
if (
ctx.header["if-none-match"] === Etag ||
ctx.header["if-modified-since"] === stat.mtime.toUTCString()
) {
ctx.status = 304;
} else {
ctx.set("ETag", Etag);
}
ctx.body = data;
});
router.use("/cache", cacheRouter.routes());
module.exports = router.routes();
前端demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>测试</title>
</head>
<body>
<div id="app">
<h1 style="text-align: center;">{{title}}</h1>
<ul>
<li v-for="item in list" :key="item.id">
{{item.name}} | {{item.address}}
</li>
</ul>
<button @click="query()">重新请求</button>
</div>
</body>
</html>
<script src="../../static/lib/axios.min.js"></script>
<script src="../../static/lib/vue-min.js"></script>
<script>
new Vue({
el: "#app",
data() {
return {
list: [],
title: "",
time: ""
};
},
mounted() {
this.query();
},
methods: {
query() {
axios
.get("http://192.168.50.226:8888/cache/eTag", {
headers: {
"if-none-match": this.time ? this.time : undefined
}
})
.then(res => {
console.log(111, res.request.getAllResponseHeaders());
this.time = res.headers["Etag"];
this.list = res.data.list;
this.title = res.data.title;
});
}
}
});
</script>