Fetch(), How to Make a Non-Cached Request

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

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>

Fetch caching response - no-cache headers not working as expected

I have managed to fix it by appending Date.now() to the url. I don't really like it as a permanent solution as it doesn't address the underlying caching issue but it works.

fetch(this.url+ Date.now(), {cache: 'no-store'})
.then(res => res.json())

Service worker ignores the fetch cache setting

I think this is a Chrome bug:
https://bugs.chromium.org/p/chromium/issues/detail?id=1317680

I guess I will just use a custom header or Cache-Control header until its sorted out.

Using JavaScript Axios/Fetch. Can you disable browser cache?

Okay so I found a solution. I had to set a timestamp on the API url to get it to make a new call. There doesn't seem to be a way to force axios or fetch to disable cache.

This is how my code now looks

axios.get(`https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1×tamp=${new Date().getTime()}`)
.then(response => {
const { title, content, link } = response.data[0];
console.log(title, content, link)
this.setState(() => ({ title, content, link }));
})
.catch(err => {
console.log(`${err} whilst contacting the quote API.`)
})


Related Topics



Leave a reply



Submit