Get and Post method using Fetch API - GeeksforGeeks

17 Sep, 2021
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object.The basic syntax of a fetch() request is as follows:  
javascript
fetch(url, {options}).then(data => {    // Do some stuff here}).catch(err => {    // Catch and display errors})
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 requests 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:  
html
<!DOCTYPE html><html lang="en">  <head>    <title>Fetch API</title>  </head>  <body>    <div>      <h1>Fetch API GET REQUEST</h1>      <h3>Fetching Users</h3>       <!-- Table to display fetched user data -->      <table id="users"></table>    </div>          <!-- Link JavaScript file -->    <script src="main.js"></script>  </body></html>
In JavaScript, file contains the following code  
javascript
//  main.js  //  GET request using fetch()fetch("https://jsonplaceholder.typicode.com/users")       // Converting received data to JSON    .then(response => response.json())    .then(json => {          // Create a variable to store HTML        let li = `<tr><th>Name</th><th>Email</th></tr>`;               // Loop through each data and add a table row        json.forEach(user => {            li += `<tr>                <td>${user.name} </td>                <td>${user.email}</td>                    </tr>`;        });      // Display result    document.getElementById("users").innerHTML = li;});
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.In the same JavaScript file add the following content:  
javascript
//  main.js  // POST request using fetch()fetch("https://jsonplaceholder.typicode.com/posts", {         // Adding method type    method: "POST",         // Adding body or contents to send    body: JSON.stringify({        title: "foo",        body: "bar",        userId: 1    }),         // Adding headers to the request    headers: {        "Content-type": "application/json; charset=UTF-8"    }}) // Converting to JSON.then(response => response.json()) // Displaying results to console.then(json => console.log(json));
Now if you open your javascript console and refresh the page you’ll see a result like below –  
The API returns a status of 201 which is a HTTP status code for Created. 
abhishek0719kadiyan
Picked
Web-API
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method