Skip to content
Related Articles

Related Articles

JavaScript | fetch() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Jun, 2022

The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

Syntax:

fetch('url')           //api for the get request
  .then(response => response.json())
  .then(data => console.log(data));

Parameters: This method accepts two parameters as mentioned above and described below:

  • 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 1:

NOTE: Without options, Fetch will always act as a get request.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0">
    <title>JavaScript | fetch() Method</title>
</head>
<body>
    <script>
        // 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)
            })
    </script>
</body>
</html>

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

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
       content="width=device-width, initial-scale=1.0">
    <title>JavaScript | fetch() Method</title>
</head>
<body>
    <script>
        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)
            })
    </script>
</body>
</html>

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!