javascript-fetch(),如何发出未缓存的请求?

使用fetch(),可以请求从服务器而不是从浏览器缓存中获取文件?

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

cc young asked 2020-01-14T08:28:21Z
3个解决方案
77 votes

提取可以获取一个包含许多自定义设置的初始化对象,您可能希望将该自定义设置应用于该请求,其中包括一个称为“标头”的选项。

“标题”选项采用一个标题对象。 该对象允许您配置要添加到请求中的标头。

通过在标题中添加pragma:no-cache和cache-control:no-cache,您将强制浏览器检查服务器,以查看文件是否与缓存中已有的文件不同。 您还可以使用cache-control:no-store,因为它只是不允许浏览器和所有中间缓存来存储返回响应的任何版本。

这是一个示例代码:

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

希望这可以帮助。

burningfuses answered 2020-01-14T08:30:04Z
55 votes

更容易使用缓存模式:

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

MJ Vakili answered 2020-01-14T08:30:28Z
10 votes

您可以在标题中设置'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);
});
Agu Dondo answered 2020-01-14T08:30:48Z
translate from https://stackoverflow.com:/questions/29246444/fetch-how-do-you-make-a-non-cached-request