I'm trying to use the HTTP Cache for something simple, but I can't get it to work.
I'm using the following options for fetch()
.
fetch('test', {
cache: 'force-cache',
headers: {
'Cache-Control': 'max-age=3600',
'Pragma': 'max-age=3600', // added for redundancy
}
})
.then( response => response.json() )
.then( data => console.log(data) )
.catch( error => console.error(error) )
.finally( () => console.log('Done') );
The test
endpoint simply returns a json with the following format
{
"date": "...", /* date in 'Y-m-d H:i:s' format */
}
I've made sure the response has the Cache-Control header as well. I can see it when I inspect the response headers.
HTTP/1.1 200 OK Server: Apache Cache-Control: public, max-age=3600 Content-Length: 30 Keep-Alive: timeout=5, max=94 Connection: Keep-Alive Content-Type: application/json; charset=UTF-8
The request headers also seem to be correct.
Connection: keep-alive Pragma: max-age=3600 Cache-Control: max-age=3600 Accept: */* Sec-Fetch-Site: same-origin Sec-Fetch-Mode: cors Sec-Fetch-Dest: empty
I tried to just run that same fetch over and over in the span of a minute, expecting to get the same date, unchanged but the results were always "new" so to speak.
Do I have a fundamental misunderstanding of how HTTP Cache works or am I better off just caching the value in the back-end?
I'm currently testing by running the following code inside a <script>
tag.
let x = 0;
const interval_id = setInterval(() => {
fetch('test', { ... });
if (++x === 20) {
window.clearInterval(interval_id);
}
}, 1500);
I'm expecting to be returned the same datetime 20 times (cache the first response)
<script>
tag because I thought the console could have somethign to do with the cache not being used but it still doesn't seem to be caching the response. – Gluck