Sometimes, we want to return HTML with fetch() and JavaScript.
In this article, we’ll look at how to return HTML with fetch() and JavaScript.
How to return HTML with fetch() and JavaScript?
To return HTML with fetch() and JavaScript, we can use the response text
method.
For instance, we write
const fetchMyDocument = async () => {
try {
const response = await fetch("/path/to/file.html");
document.body.innerHTML = await response.text();
} catch (err) {
console.log(err);
}
};
to call fetch
to make a GET request to "/path/to/file.html"
.
Then we get the response
from the promise returned by fetch
.
Finally, we get the response body HTML from the promise returned by the response.text
method with await
.
Conclusion
To return HTML with fetch() and JavaScript, we can use the response text
method.