Simple POST request using the fetch API

The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API

Syntax:

  • fetch(url, { config }) 
    .then(res => { 
        // Handle response 
    }) 
    .catch(err => { 
        // Handle errors 
    }) 
    
  • Since fetch returns a Promise, we can also use async/await keywords to make requests:
    async () => {
      const resp = await fetch('http://example.com/example.json');
      // Handle response
    }
    

Create a POST request using fetch(): The POST request is widely used to submit forms to the server.

filter_none

edit
close

play_arrow

link
brightness_4
code

fetch(url, {
    method: 'POST',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    credentials: 'include',
    body: 'foo=bar&lorem=ipsum'
  })
  .then(res.json())
  .then(res => {
    // Handle response 
    console.log('Response: ', res);
  })
  .catch(err => {
    // Handle error 
    console.log('Error message: ', error);
  });

chevron_right


Explanation:

  • To create a POST request we need to specify some parameters with the request such as method, headers, etc. First, we need to specify the request method (GET, POST, DELETE, etc.) which is POST in our case. This is followed by the Content-type, which tells the client what the content type of the returned data actually is. The credentials key is optional and should be used if you want to make a fetch request with credentials such as cookies. Then we set the body which consists of the data we wish to pass to the server.
  • The response of a fetch() request is a stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
  • If the API returns a status of 201 (the HTTP status code for Created), the data returned by the API can be accessed- res(response). In case an error occurs, the code inside the catch block will be executed.
My Personal Notes arrow_drop_up

Data Structure & Algorithms Lead (C++) Developer Student Club (Google) || MERN Stack Web Developer || Machine Learning Enthusiast || Skilled in C, C++, Java, Python, HTML, CSS, JS, React, NodeJS, Mongoose, Git among others

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.