![]() |
VOOZH | about |
The fetch() method is used to send HTTP requests to the server without refreshing the page, providing an efficient alternative to the older XMLHttpRequest object. One of the main advantages of fetch() is that it uses Promises, which allow for better management of asynchronous operations compared to callbacks. Promises help avoid "callback hell," where nested callbacks can become difficult to read and maintain.
However, it's worth noting that not all browsers support fetch() natively. For older browsers, you may still need to rely on the XMLHttpRequest object or use polyfills to ensure compatibility.
The fetch() method can handle different types of HTTP requests, such as GET, POST, PUT, and DELETE. In this article, we'll explore how to use the fetch() API with practical examples.
The basic syntax for a fetch() request looks like this:
A GET request is used to retrieve data from a server. Let’s use https://jsonplaceholder.typicode.com/, a free REST API that returns sample data such as posts and users.
First, create a basic HTML file that includes a JavaScript script where we’ll make our fetch requests.
In the JavaScript file (e.g., script.js), write the following code to fetch user data from the API:
Now, when you open the HTML file you'll see the result as follows:
When you open DevTools in Chrome (Press F12) you'll see that a fetch request has been made to the route users.
You can get more data from the request, refer to the https://jsonplaceholder.typicode.com/guide/documentation.
A POST request is used to send data to the server, commonly for submitting forms or adding new data. In this example, we'll send a POST request to add a new post to the posts endpoint of the JSONPlaceholder API. The server will return the created post with a unique ID.
Add the following code to your script.js file to perform a POST request:
Now if you open your javascript console and refresh the page you'll see a result like below:
👁 Image
The API returns a status of 201 which is a HTTP status code for Created.
It's important to note that fetch() will only reject a Promise if there’s a network failure. It does not automatically reject responses with a status code outside the 2xx range (such as 404 or 500 errors). Therefore, you must manually check the response status using response.ok.