The Wayback Machine - https://web.archive.org/web/20240112035332/https://www.geeksforgeeks.org/javascript-fetch-method/
Open In App
Related Articles

JavaScript fetch() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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




// API for get requests
let fetchRes = fetch(
     
// FetchRes is the promise to resolve
// it by using.then() method
fetchRes.then(res =>
    res.json()).then(d => {
        console.log(d)
    })


Output:

Image

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"
}
 
// Options to be given as parameter
// in fetch for making requests
// other then GET
let options = {
    method: 'POST',
    headers: {
        'Content-Type':
            'application/json;charset=utf-8'
    },
    body: JSON.stringify(user)
}
 
// Fake api for making post requests
let fetchRes = fetch(
    options);
fetchRes.then(res =>
    res.json()).then(d => {
        console.log(d)
    })


Output:

Image


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
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials