How to use the Fetch API to get HTML response in JavaScript

published: 18 Apr 2022

2 min read

How to use the Fetch API to get HTML response in JavaScript

JavaScript Fetch API is a modern and versatile alternative to traditional built-in XMLHttpRequest (XHR) object for making network requests. It also supports promises which makes it easier to write asynchronous code.

The Response object returned by the fetch() method contains the information about the request and the response of the network request including headers, status code, and status message.

The Response object provides several methods to access the response body like json(), text(), and more. To get a response as an HTML string, you can use the text() method.

Here is an example that downloads the Google homepage as an HTML string and prints it on the console:

fetch('https://www.google.com')
    .then(res => res.text())
    .then(res => console.log(res))
    .catch(err => console.error(err));

The text() method returns the response body as a string. Take a look at this section to learn more about Fetch API response formats.

How to use the Fetch API to get HTML response in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, json