JavaScript fetch() method is used to request data from a server. The request can be of any type of API that returns the data in JSON or XML. The fetch() method requires one parameter, the URL to request, and returns a promise.
Syntax:
fetch('url') //api for the get request
.then(response => response.json())
.then(data => console.log(data));
Parameters:
- URL: It is the URL to which the request is to be made.
- Options: It is an array of properties. It is an optional parameter.
Return Value:
It returns a promise whether it is resolved or not. The return data can be of the format JSON or XML. It can be an array of objects or simply a single object.
Example: This example shows the use of the javascript fetch() method.
NOTE: Without options, Fetch will always act as a get request.
Javascript
let fetchRes = fetch(
fetchRes.then(res =>
res.json()).then(d => {
console.log(d)
})
|
Output:

Making Post Request using Fetch
Post requests can be made using fetch by giving options as given below:
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(data)
}
Example: In this example, we will see the use of the post method in fetch() in javascript.
Javascript
user = {
"name": "Geeks for Geeks",
"age": "23"
}
let options = {
method: 'POST',
headers: {
'Content-Type':
'application/json;charset=utf-8'
},
body: JSON.stringify(user)
}
let fetchRes = fetch(
options);
fetchRes.then(res =>
res.json()).then(d => {
console.log(d)
})
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
24 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...