这是否意味着在 100 秒内,后续请求将永远不会向服务器请求?所有这些请求都只是在缓存中收到响应?
除非后续请求使用Cache-Control 标头对缓存进行更多控制,否则请求只会从缓存中获取响应数据。
如果后续请求中包含了headerCache-Control:no-cache或Cache-Control:max-age=0,即使缓存没有过期,100秒内是否会向原服务器请求?
是的,它将向原始服务器发送 HTTP 请求。请求标头中的Cache-Control:no-cache 表示:“除非重新验证资源,否则浏览器不会从缓存中接受它”。请求头中的Cache-Control:max-age=<n> 表示:“浏览器不会接受任何超过 n 秒的缓存”——当 n 为 0 时,浏览器将始终向服务器发送请求。
这是一个简单的实验。
在浏览器中:
var poll = function() {
$.ajax({
url: '/poll',
beforeSend: function(xhr) {
//xhr.setRequestHeader('Cache-Control', 'no-cache');
//xhr.setRequestHeader('Cache-Control', 'max-age=0');
},
success: function(){
setTimeout(poll, 5000);
}
});
}
poll();
在服务器中:
http.createServer(function(req,res) {
...
// if request path is /poll
res.setHeader('Cache-Control', 'max-age=18');
res.end();
})
你可以观察到:
- 当
/poll请求不包含Cache-Control头时,浏览器会向源服务器发送请求,为接下来的3个请求从缓存中获取资源,然后再次向源服务器发送请求...
- 当
/poll 请求的“Cache-Control”标头为no-cache 或max-age=0 时,浏览器将始终向源服务器发送请求。
请注意,在 Chrome 上执行此实验时,需要在 DevTool 中取消选中 Disable cache。