Posts Learn Components Snippets Categories Tags Tools About
/

Send a POST Request with a Fetch API in JavaScript

Learn how to create a resource from the front-end with fetch to call an external API with the POST method.

Created on Aug 29, 2021

507 views

In this short snippet, you will learn how to create a resource from the front-end with the fetch API to call an external endpoint with the POST method.

Fetch with POST method


In this code example, we are calling a dummy API for testing. We will create a new "posts" resource that will have the following endpoint.
http://jsonplaceholder.typicode.com/posts
The code example will be as follows. It's very important to keep note that each of the code section is included. The 1st parameter is the URL to the resource, 2nd is an object that has the data for the request. In this case it will be the "method" to use, the request "body" and also "header",
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

Code Output


Since by default the JSON placeholder API "posts" resource has 100 records, posting a new resource will create a post with id 101.
{
  id: 101,
  title: 'foo',
  body: 'bar',
  userId: 1
}
Important: resource will not be really updated on the server but it will be faked as if.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)