Reputation: 1528
I have a bunch of REST APIs which send cache-control
as public, only-if-cached, max-stale=2419200, max-age=60
max-age=60
makes sure that if the client sends an identical API request, the client picks the response from the cache instead of forwarding it to the server for a fresh response.
Now, this works perfectly for our mobile app because it is read only and a minute delay in data update is acceptable. However, the website, which uses the same set of APIs to add/ delete data, needs to be real-time i.e. always ignore the max-age=60
part of the header. Since, currently, the caching header is not ignored all PUT, PATCH or DELETE request reflect the changes only after a minute.
Is there any way I can let my website to ignore cache-control
. The web pages are written in plain JS and HTML. JS uses fetch
for all REST requests.
Upvotes: 2
Views: 6724
Reputation: 2943
You can disable cache in fetch by appending in headers
var headers = new Headers();
headers.append('pragma', 'no-cache');
headers.append('cache-control', 'no-cache');
var init = {
method: 'GET',
headers: headers,
};
var request = new Request(YOUR_URL);
fetch(request, init)
.....
You can also use cache-control: no-store
, which will never store a cache version.
alternately, you can use a dynamic string in URL, it will still store a version in your browser's cache , like
const ms = Date.now();
const data = await fetch(YOUR_URL+"?t="+ms)
Upvotes: 1
Reputation: 2630
Implement Timestamped Requests Logic:
Append timestamp to each of the requests. With the help of a javascript utility method something like below, this method will append time stamp to all the requests urls along with the exisitng query params to the URL if exists.
private getTimeStampedUrl(url:string){
var timestamp = Date.now();
var timestampedUrl = (url.indexOf('?') == -1) ? url + '?' : url + '&';
timestampedUrl += 'timestamp=' + timestamp;
return timestampedUrl;
}
This will treat each of the requests as new requests from browser and caching will not be working. In general, browser cache works if we send similar requests, which we are breaking here, by appending unique time stamps to each requests.
Upvotes: 0