The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the
The basic syntax of a fetch() request is as follows:
The difference between XMLHttpRequest and fetch is that fetch uses Promises which are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
However there are still some browsers that do not support fetch() method, so for those, we have to stick with the XMLHttpRequest object.
A fetch() method can be used with many type of reuqests such as POST, GET, PUT and DELETE.
GET method using fetch API:
In this example, we are going to use JSONPlaceholder which provides REST API get and post random data such as posts, users, etc.
First of all, create an HTML file with the following code:
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 documentation.
POST request using fetch API:
The post request is widely used to submit forms to the server. Fetch also supports the POST method call. To do a POST request we need to specify additional parameters with the request such as method, headers, etc.
In this example, we’ll do a POST request on the same JSONPlaceholder and add a post in the posts. It’ll then return the same post content with an ID.
The API returns a status of 201 which is a HTTP status code for Created.
- Simple GET and POST request using Fetch API method by making custom HTTP library
- Simple POST request using the fetch API
- AngularJS | fetch data from API using HttpClient
- How to make simple PUT request using fetch API by making custom HTTP library ?
- Simple DELETE request using fetch API by making custom HTTP library
- Fetch API
- D3.js d3-Fetch API
- How to fetch data from localserver database and display on HTML table using PHP ?
- How to fetch data from JSON file and display in HTML table using jQuery ?
- How to fetch single and multiple documents from MongoDb using Node.js ?
- How to get form data using POST method in PHP ?
- PHP program to fetch data from localhost server database using XAMPP
- How to fetch the details using ng-repeat in AngularJS?
- How to fetch data from Database in PHP PDO using loop ?
- Difference between REST API and SOAP API
- Difference between Fetch and Axios.js for making http requests
- HTTP GET and POST Methods in PHP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.