fetch(), how do you make a non-cached request?

JavascriptHtmlFetch Api

Javascript Problem Overview


with fetch('somefile.json'), it is possible to request that the file be fetched from the server and not from the browser cache?

in other words, with fetch(), is it possible to circumvent the browser's cache?

Javascript Solutions


Solution 1 - Javascript

Fetch can take an init object containing many custom settings that you might want to apply to the request, this includes an option called "headers".

The "headers" option takes a Header object. This object allows you to configure the headers you want to add to your request.

By adding pragma: no-cache and a cache-control: no-cache to your header you will force the browser to check the server to see if the file is different from the file it already has in the cache. You could also use cache-control: no-store as it simply disallows the browser and all intermediate caches to store any version of the returned response.

Here is a sample code:

var myImage = document.querySelector('img');

var myHeaders = new Headers();
myHeaders.append('pragma', 'no-cache');
myHeaders.append('cache-control', 'no-cache');

var myInit = {
  method: 'GET',
  headers: myHeaders,
};

var myRequest = new Request('myImage.jpg');

fetch(myRequest, myInit)
  .then(function(response) {
    return response.blob();
  })
  .then(function(response) {
    var objectURL = URL.createObjectURL(response);
    myImage.src = objectURL;
  });

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ES6</title>
</head>
<body>
    <img src="">
</body>
</html>

Hope this helps.

Solution 2 - Javascript

Easier use of cache modes:

  // Download a resource with cache busting, to bypass the cache
  // completely.
  fetch("some.json", {cache: "no-store"})
    .then(function(response) { /* consume the response */ });

  // Download a resource with cache busting, but update the HTTP
  // cache with the downloaded resource.
  fetch("some.json", {cache: "reload"})
    .then(function(response) { /* consume the response */ });

  // Download a resource with cache busting when dealing with a
  // properly configured server that will send the correct ETag
  // and Date headers and properly handle If-Modified-Since and
  // If-None-Match request headers, therefore we can rely on the
  // validation to guarantee a fresh response.
  fetch("some.json", {cache: "no-cache"})
    .then(function(response) { /* consume the response */ });

  // Download a resource with economics in mind!  Prefer a cached
  // albeit stale response to conserve as much bandwidth as possible.
  fetch("some.json", {cache: "force-cache"})
    .then(function(response) { /* consume the response */ });

refrence:https://hacks.mozilla.org/2016/03/referrer-and-cache-control-apis-for-fetch/

Solution 3 - Javascript

You can set 'Cache-Control': 'no-cache' in the header like this::

return fetch(url, {
  headers: {
    'Cache-Control': 'no-cache'
  }
}).then(function (res) {
  return res.json();
}).catch(function(error) {
  console.warn('Failed: ', error);
});

Solution 4 - Javascript

None of the solutions seemed to work well for me, but this relatively clean (AFAICT) hack did work (adapted from https://webmasters.stackexchange.com/questions/93594/prevent-browser-from-caching-text-file):

  const URL = "http://example.com";
  const ms = Date.now();
  const data = await fetch(URL+"?dummy="+ms)
	.catch(er => game_log(er.message))
    .then(response => response.text());

This is just adding a dummy parameter that changes on every call to a query. By all means, if other solutions appear to work, I suggest using those, but in my tests, they did not work in my case (e.g. those using Cache-Control and pragram).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncc youngView Question on Stackoverflow
Solution 1 - JavascriptburningfusesView Answer on Stackoverflow
Solution 2 - JavascriptMJ VakiliView Answer on Stackoverflow
Solution 3 - JavascriptAgu DondoView Answer on Stackoverflow
Solution 4 - JavascriptbbarkerView Answer on Stackoverflow