Categories
JavaScript Answers

How to make a non-cached request with fetch and JavaScript?

Spread the love

Sometimes, we want to make a non-cached request with fetch and JavaScript.

In this article, we’ll look at how to make a non-cached request with fetch and JavaScript.

How to make a non-cached request with fetch and JavaScript?

To make a non-cached request with fetch and JavaScript, we can set the pragma and cache-control request headers.

For instance, we write

const myImage = document.querySelector("img");

const headers = new Headers();
myHeaders.append("pragma", "no-cache");
myHeaders.append("cache-control", "no-cache");

const myInit = {
  method: "GET",
  headers,
};

const myRequest = new Request("myImage.jpg");

const response = await fetch(myRequest, myInit);
const blob = await response.blob();
const objectURL = URL.createObjectURL(blob);
myImage.src = objectURL;

to call fetch with myRequest and myInit.

In myInit, we set the headers to the headers object.

We set the pragma header to 'no-cache' and cache-control to 'no-cache with append to make a non-cached request.

Then we get the blob from the response with blob.

Conclusion

To make a non-cached request with fetch and JavaScript, we can set the pragma and cache-control request headers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to make a non-cached request with fetch and JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *