Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch(), how do you make a non-cached request?

with fetch('somefile.json'), it is possible to request that the file be fetched from the server and not from the browser cache?

in other words, with fetch(), is it possible to circumvent the browser's cache?

like image 204
cc young Avatar asked Mar 25 '15 02:03

cc young


People also ask

Are fetch requests cached?

The resources downloaded through fetch(), similar to other resources that the browser downloads, are subject to the HTTP cache. This is usually fine, since it means that if your browser has a cached copy of the response to the HTTP request.

How do I make a fetch request?

GET request using fetch() method:createObjectURL() method that creates a DOMString containing a URL representing the object. Finally, we create an IMG element and place the data fetched into the <img> element.

Does fetch send a GET request?

With the fetch() function, we can make GET and POST requests to different URLs. We can configure a fetch() requests to use any HTTP method we want to use. The fetch() function also provides a response object that can be parsed into various formats. These include JSON, text, and bytes to name a few.

How do I change content-type in Fetch?

To set the content-type of request header when using Fetch API with JavaScript, we can put the header in a Header object. const options = { method, headers: new Headers({ "content-type": "application/json" }), mode: "no-cors", body: JSON. stringify(body), }; await fetch(url, options);


1 Answers

Fetch can take an init object containing many custom settings that you might want to apply to the request, this includes an option called "headers".

The "headers" option takes a Header object. This object allows you to configure the headers you want to add to your request.

By adding pragma: no-cache and a cache-control: no-cache to your header you will force the browser to check the server to see if the file is different from the file it already has in the cache. You could also use cache-control: no-store as it simply disallows the browser and all intermediate caches to store any version of the returned response.

Here is a sample code:

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>

Hope this helps.

like image 127
burningfuses Avatar answered Oct 13 '22 01:10

burningfuses