Heim  >  Fragen und Antworten  >  Hauptteil

fetch(), wie stellt man eine nicht zwischengespeicherte Anfrage?

<p>Kann ich mit <code>fetch('somefile.json')</code> eine Datei vom Server anstelle des Browser-Cache anfordern? </p> <p>Mit anderen Worten: Ist es möglich, den Cache des Browsers mit <code>fetch()</code> zu umgehen? </p>
P粉214176639P粉214176639391 Tage vor418

Antworte allen(2)Ich werde antworten

  • P粉731977554

    P粉7319775542023-08-28 17:40:52

    更轻松地使用缓存模式:

    // 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/

    Antwort
    0
  • P粉395056196

    P粉3950561962023-08-28 10:56:27

    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>

    Antwort
    0
  • StornierenAntwort