The Response interface of the Fetch API represents the response to a request.
You can create a new Response object using the Response() constructor, but you are more likely to encounter a Response object being returned as the result of another API operation—for example, a service worker FetchEvent.respondWith, or a simple fetch().
In our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> element. The fetch() call returns a promise, which resolves to the Response object associated with the resource fetch operation.
You'll notice that since we are requesting an image, we need to run Response.blob to give the response its correct MIME type.
const image = document.querySelector(".my-image");
fetch("flowers.jpg")
.then((response) => response.blob())
.then((blob) => {
const objectURL = URL.createObjectURL(blob);
image.src = objectURL;
});
You can also use the Response() constructor to create your own custom Response object:
const response = new Response();
Here we call a PHP program file that generates a JSON string, displaying the result as a JSON value, including simple error handling.
const doAjax = async () => {
const response = await fetch("Ajax.php");
if (response.ok) {
return response.json();
}
throw new Error("*** PHP file not found");
};
doAjax().then(console.log).catch(console.log);