Get and Post method using Fetch API - GeeksforGeeks (2024)

Last Updated : 21 May, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

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:

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 https://jsonplaceholder.typicode.com/ 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()

// 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:

Get and Post method using Fetch API - GeeksforGeeks (2)

When you open DevTools in Chrome (Press F12) you’ll see that a fetch request has been made to the route users.

Get and Post method using Fetch API - GeeksforGeeks (3)

You can get more data from the request, refer to the https://jsonplaceholder.typicode.com/guide/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()

// 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 –

Get and Post method using Fetch API - GeeksforGeeks (4)

The API returns a status of 201 which is a HTTP status code for Created.



Get and Post method using Fetch API - GeeksforGeeks (6)

Improve

Please Login to comment...

Get and Post method using Fetch API - GeeksforGeeks (2024)
Top Articles
17 Fantastic Jobs You Can Do While Traveling To Make Money
Best Business Insurance Companies of 2024
Sprinter Tyrone's Unblocked Games
Urist Mcenforcer
Dollywood's Smoky Mountain Christmas - Pigeon Forge, TN
How Many Cc's Is A 96 Cubic Inch Engine
Overnight Cleaner Jobs
Do you need a masters to work in private equity?
Comcast Xfinity Outage in Kipton, Ohio
35105N Sap 5 50 W Nit
Mikayla Campinos Videos: A Deep Dive Into The Rising Star
PGA of America leaving Palm Beach Gardens for Frisco, Texas
Craigslist Free Grand Rapids
Richmond Va Craigslist Com
I Wanna Dance with Somebody : séances à Paris et en Île-de-France - L'Officiel des spectacles
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Trac Cbna
50 Shades Of Grey Movie 123Movies
Forum Phun Extra
Aris Rachevsky Harvard
What Is Vioc On Credit Card Statement
Ruse For Crashing Family Reunions Crossword
Hdmovie2 Sbs
12 Top-Rated Things to Do in Muskegon, MI
All Breed Database
Air Quality Index Endicott Ny
Cookie Clicker Advanced Method Unblocked
Used Patio Furniture - Craigslist
Accuradio Unblocked
Catchvideo Chrome Extension
Ocala Craigslist Com
His Only Son Showtimes Near Marquee Cinemas - Wakefield 12
10 Best Quotes From Venom (2018)
Scat Ladyboy
Suspect may have staked out Trump's golf course for 12 hours before the apparent assassination attempt
Mta Bus Forums
Studio 22 Nashville Review
How To Paint Dinos In Ark
National Insider Threat Awareness Month - 2024 DCSA Conference For Insider Threat Virtual Registration Still Available
Sc Pick 4 Evening Archives
Compare Plans and Pricing - MEGA
Low Tide In Twilight Manga Chapter 53
Andrew Lee Torres
Sofia Franklyn Leaks
Exploring the Digital Marketplace: A Guide to Craigslist Miami
Juiced Banned Ad
Rs3 Nature Spirit Quick Guide
Bmp 202 Blue Round Pill
The Average Amount of Calories in a Poke Bowl | Grubby's Poke
Provincial Freeman (Toronto and Chatham, ON: Mary Ann Shadd Cary (October 9, 1823 – June 5, 1893)), November 3, 1855, p. 1
Loss Payee And Lienholder Addresses And Contact Information Updated Daily Free List Bank Of America
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5821

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.