Making network requests is a fundamental aspect of building modern web applications. The Fetch API, introduced in ES6, provides an easy-to-use interface for fetching resources (such as JSON data or HTML content) from a server.
A GET request is a type of HTTP request method that is used to retrieve data from the server.
In this article, we will learn how to send a GET request using the Fetch API in JavaScript.
GET request using fetch() in JavaScript
The basic syntax for sending a GET request using the Fetch API is as follows:
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
In the above code, we first call the fetch()
function with the URL of the resource we want to fetch. This function returns a Promise that resolves to the response of the server. We then use the .then()
method to extract the JSON data from the response and log it to the console. Finally, we use the .catch()
method to handle any errors that might occur.
Let’s break down the code line by line:
fetch(url);
Here, we are calling the fetch()
function with the URL of the resource we want to fetch. The fetch()
function returns a Promise that resolves to the response of the server.
.then(response => response.json())
Once the Promise returned by fetch()
resolves, we use the .then()
method to extract the JSON data from the response. In this example, we are using the .json()
method to convert the response to a JSON object.
If the response is not JSON, we can use other methods like .text()
or .blob()
to extract the response in other formats.
.then(data => console.log(data))
Once we have extracted the JSON data from the response, we can log it to the console or use it in our application.
.catch(error => console.error(error));
Finally, we use the .catch()
method to handle any errors that might occur during the request. If an error occurs, we log it to the console.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.