[TOC]
控制緩存的字段都是通過后臺服務器進行設置的
如: 使用node.js開啟服務(運行:node serve.js)
### 1. Cache-Control控制是否緩存
~~~
// Cache-Control
const http =require('http');
const fs=require('fs')
http.createServer(function(request,response){
// console.log('request come', request.url)
if (request.url==='/'){
const html=fs.readFileSync('001.html','utf8')
response.writeHead(200,{
// 'Access-Control-Allow-Origin':"*",
'Content-Type':'text/html',
'Cache-Control':'max-age=10'
})
response.end(html)
}
if (request.url==='/script.js'){
response.writeHead(200,{
'Access-Control-Allow-Origin':"*",
'Content-Type':'text/javascript',
'Cache-Control':'max-age=10'
})
response.end('console.log("111222")')
}
}).listen(8887)
console.log("serve lestening on 8887")
~~~
### 2. Etag判斷是否協商緩存
~~~
// Etag
//說明:Cache-Control設置了max-age=10說明是允許瀏覽器緩存數據,設置了no-cache說明不能直接使用緩存還是要去服務端進行請求,看是否需要使用緩存,也就是協商緩存
//協商緩存:首次訪問時如果設置了Last-Modified(上次訪問時間)和Etag(數據簽名,數據修改后簽名改變),那么二次訪問的情況下會在請求頭中帶if-none-match,然后拿這個值和Etag比較判斷是否更新是否使用緩存
//第二次訪問雖然是304,雖然向服務器發送請求但還是從緩存中取的數據。雖然在返回304的時候 寫入了123,response.end('123')。
const http =require('http');
const fs=require('fs')
http.createServer(function(request,response){
// console.log('request come', request.url)
if (request.url==='/'){
const html=fs.readFileSync('001.html','utf8')
response.writeHead(200,{
'Content-Type':'text/html',
'Cache-Control':'max-age=10'
})
response.end(html)
}
if (request.url==='/script.js'){
const etag=request.headers['if-none-match'];
if(etag==='777'){
response.writeHead(304,{
'Content-Type':'text/javascript',
'Cache-Control':'max-age=1000000',
'Last-Modified':'123',
'Etag':'777'
})
response.end('123')
}else{
response.writeHead(200,{
'Content-Type':'text/javascript',
'Cache-Control':'max-age=10000000',
'Last-Modified':'123',
'Etag':'777'
})
response.end('12345')
}
}
}).listen(8887)
console.log("serve lestening on 8887")
~~~
### 3. no-cache與no-store的區別
~~~
設置了no-cache說明不能直接使用緩存還是要去服務端進行請求,看是否需要使用緩存,也就是協商緩存
在上面基礎上將Cache-Control中的no-cache換成no-store,表示瀏覽器不會使用緩存數據,
~~~
### 4. cookie的設置及參數
~~~
// cookie 設置cookies的方式max-age表示cookie多久之后過期,domain=test.com設置已什么結尾的網站都通用cookie
// HttpOnly 表示不允許js訪問cookie (js訪問方式為:document.cookie)
const http =require('http');
const fs=require('fs')
http.createServer(function(request,response){
// console.log('request come', request.url)
const host =request.headers.host;
if (request.url==='/'){
// if(host ==='test.com'){
const html=fs.readFileSync('001.html','utf8');
response.writeHead(200,{
'Content-Type':'text/html',
'Set-Cookie':['id=123;max-age=10','abc=456;domain=test.com','def=111, HttpOnly']
})
response.end(html)
}
// }
}).listen(8887)
console.log("serve lestening on 8887")
~~~