fetch(), how to make a non-cached request?
P粉214176639
P粉214176639 2023-08-27 18:47:06
0
2
457
<p>Using <code>fetch('somefile.json')</code>, can I request a file from the server instead of the browser cache? </p> <p>In other words, is it possible to bypass the browser's cache using <code>fetch()</code>? </p>
P粉214176639
P粉214176639

reply all(2)
P粉731977554

Easier use of cached mode:

// 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 */ });

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

P粉395056196

Fetch You can get an init object that contains many customizations you might want to apply to your request, including an option called "Headers".

The "headers" option takes a Header object. This object allows you to configure headers to be added to the request.

By adding pragma: no-cache and cache-control: no-cache in the header, you will force the browser to check the server to see if the file exists with the cache are different from the existing files in . You can also use cache-control: no-store as it just doesn't allow the browser and all intermediate cache stores to return any version of the 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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template