fetch(),你如何进行非缓存请求?

时间:2015-03-25 02:29:16

标签: javascript html5 fetch-api

使用fetch('somefile.json'),可以请求从服务器而不是浏览器缓存中提取文件吗?

换句话说,使用fetch(),是否有可能规避浏览器的缓存?

4 个答案:

答案 0 :(得分:67)

Fetch可以包含一个init对象,其中包含许多您可能希望应用于请求的自定义设置,其中包括一个名为" headers"的选项。

"标题"选项需要Header个对象。此对象允许您配置要添加到请求中的标头。

通过向您的标头添加 pragma:no-cache 缓存控制: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>
&#13;
&#13;
&#13;

希望这有帮助。

答案 1 :(得分:43)

更容易使用缓存模式:

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

答案 2 :(得分:7)

您可以在标题中设置'Cache-Control': 'no-cache',例如::

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

答案 3 :(得分:0)

这些解决方案似乎都不适合我,但是这种相对干净的(AFAICT)黑客确实起作用了(改编自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());

这只是添加一个虚拟参数,该参数在每次查询调用时都会更改。无论如何,如果其他解决方案似乎可行,我建议使用这些解决方案,但在我的测试中,它们不适用于我的情况(例如,使用Cache-Controlpragram的解决方案)。

相关问题