瀏覽器快取與緩存(Etag, If-None-Match)
瀏覽器快取與緩存(Etag 與 If-None-Match)
為何要用:
範例:

範例


注意事項:
如果是 expressjs server 已經實作了 304 回應


Last updated





Last updated
const http = require('http');
const fs = require('fs');
const etag = require('etag');
const server = http.createServer(function (req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTION, PUT, POST, DELETE');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.url === '/test') {
fs.readFile("./test.html", function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
}
if (req.url === '/cc') {
const payload = {
a: 11112222,
c: 222
};
if (etag(JSON.stringify(payload)) === req.headers["if-none-match"]) {
res.statusCode = 304;
res.end(JSON.stringify(payload));
} else {
res.setHeader('ETag', etag(JSON.stringify(payload)))
res.end(JSON.stringify(payload))
}
}
});
server.listen(5000);
console.log('Node.js web server running at port 5000')<!doctype HTML>
<html>
<head>
<title>
Hi
</title>
<script>
fetch('http://localhost:5000/cc')
.then(data => {
console.log(data)
})
</script>
</head>
<body>
<h1>
Hello
</h1>
</body>
</html>