fetch(),如何發出非快取請求?
P粉214176639
P粉214176639 2023-08-27 18:47:06
0
2
455
<p>使用<code>fetch('somefile.json')</code>,可以要求從伺服器而不是瀏覽器快取中取得檔案嗎? </p> <p>換句話說,使用<code>fetch()</code>,是否可以繞過瀏覽器的快取? </p>
P粉214176639
P粉214176639

全部回覆(2)
P粉731977554

更輕鬆地使用快取模式:

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

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

P粉395056196

Fetch 可以取得包含許多內容的 init 物件您可能想要套用於要求的自訂設置,其中包括一個名為「標頭」的選項。

“headers”選項採用 Header 物件。該物件允許您配置要新增至請求中的標頭。

透過在標頭中新增pragma: no-cachecache-control: no-cache,您將強制瀏覽器檢查伺服器以查看該檔案是否存在與快取中已有的文件不同。您也可以使用cache-control: no-store,因為它只是不允許瀏覽器和所有中間快取儲存回傳回應的任何版本。

這裡是一個範例程式碼:

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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板