Skip to content
Related Articles

Related Articles

JavaScript | fetch() Method

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 19 Oct, 2022
Improve Article
Save Article

The fetch() method in JavaScript is used to request data from a server. The request can be of any type of API that return 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: This method requires one parameter and accepts two 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 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
Related Articles

Start Your Coding Journey Now!