Open In App

Simple POST request using the fetch API

Improve
Improve
Like Article
Like
Save
Share
Report

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.




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);
  });


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.

Last Updated : 25 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads