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?
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With