Open In App

Simple POST request using the fetch API

Last Updated : 25 May, 2020
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.

Similar Reads

Simple GET and POST request using Fetch API method by making custom HTTP library
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a dummy API that will contain an array of array as an example and we will show GET and POST data by Fetch API method by making custom HTTP library. Used API: https://jsonplaceholder.typicode
3 min read
Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript
In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resou
3 min read
How to make simple PUT request using fetch API by making custom HTTP library ?
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. It will be taking a fake API that will contain Array as an example and from that API we will show to PUT/Update data by fetch API method by making custom HTTP library. The API used in this tutorial is: https:
2 min read
Simple DELETE request using fetch API by making custom HTTP library
Why fetch() API method is used? The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a fake API which will contain Array as an example and from that API we will show to DELETE data by fetch API method by making custom HTTP library. The API use
2 min read
How to Fetch XML with Fetch API in JavaScript ?
The JavaScript fetch() method retrieves resources from a server and produces a Promise. We will see how to fetch XML data with JavaScript's Fetch API, parse responses into XML documents, and utilize DOM manipulation for streamlined data extraction with different methods. These are the following methods: Table of Content Using response.text() Method
3 min read
Pre-request and Post-request scripts in Postman
Postman is a powerful tool for testing APIs, and its pre-request and post-request scripts allow you to customize requests and responses. it is an API(utility programming interface) development device that enables construction, taking a look at and altering APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environ
4 min read
Get and Post method using Fetch API
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object.The basic syntax of a fetch() request is as follows: C/C++ Code fetch(url, {options}) .then(data => { // Do some stuff here }) .catch(err => { // Catch and display errors }) The difference between XMLHtt
3 min read
How to Replicate Postman POST API Request using AJAX ?
In this project we'll mimic the action of submitting data using POST to a server from a web page. We replicate this process using AJAX (Asynchronous JavaScript and XML) directly in a web page, we're embedding similar functionality within our own interface. This involves setting up HTML elements like input fields and buttons to gather user input, us
4 min read
What is the difference between react-fetch and whatwg-fetch in React.js ?
React-fetch and Whatwg-fetch are both libraries for making HTTP requests in a React application, but they are used for different purposes and have different features. Table of Content React-fetchWhatwg-fetchDifference between React-fetch and Whatwg-fetchReact-fetch: `react-fetch` is a library offering a higher-order component (HOC) for streamlined
2 min read
POST request using AJAX by making Custom HTTP library
The task is to show how the XMLHttpRequest can be used to POST data to an API by making custom HTTP library. We will be taking a fake API which will contain Array of objects as an example and from that API we will show to POST data by XMLHttpRequest method by making a custom HTTP library. Used API: https://jsonplaceholder.typicode.com/posts What is
4 min read