Подтвердить что ты не робот

Fetch(), как вы делаете запрос без кэширования?

с fetch('somefile.json'), можно запросить, чтобы файл был извлечен с сервера, а не из кеша браузера?

Другими словами, с fetch() можно ли обойти кеш браузера?

4b9b3361

Ответ 1

Fetch может принимать объект init, содержащий множество настраиваемых параметров, которые вы можете применить к запросу, в том числе параметр, называемый "заголовки".

Опция "заголовки" принимает объект Header. Этот объект позволяет вам настроить заголовки, которые вы хотите добавить в свой запрос.

Добавив в заголовок прагма: no-cache и кеш-контроль: no-cache, вы заставите браузер проверить сервер, чтобы узнать, отличается от файла, который он уже имеет в кеше. Вы также можете использовать управление кешем: 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>

Ответ 2

Простое использование режимов кэширования:

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

Ответ 3

Вы можете установить '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);
});