Fetch - HTTP POST Request Examples
Below is a quick set of examples to show how to send HTTP POST requests to an API using fetch()
which comes bundled with all modern browsers.
Other HTTP examples available:
- Fetch: GET, PUT, DELETE
- Axios: GET, POST, PUT, DELETE
- React + Fetch: GET, POST, PUT, DELETE
- React + Axios: GET, POST, PUT, DELETE
- Angular: GET, POST, PUT, DELETE
- Vue + Fetch: GET, POST, PUT, DELETE
- Vue + Axios: GET, POST
- Blazor WebAssembly: GET, POST
Simple POST request with a JSON body using fetch
This sends an HTTP POST request to the Reqres api which is a fake online REST api used for testing, it includes a generic /api/<resource>
route that supports POST
requests to any <resource>
and responds with the contents of the post body and a dynamic id property. This example sends an article
object to the /api/articles
route and then writes the id from the response to the #post-request .article-id
element so it's displayed on the page.
// Simple POST request with a JSON body using fetch
const element = document.querySelector('#post-request .article-id');
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
fetch('https://reqres.in/api/articles', requestOptions)
.then(response => response.json())
.then(data => element.innerHTML = data.id );
Example Fetch POST request at https://stackblitz.com/edit/fetch-http-post-request-examples?file=post-request.js
POST request using fetch with async/await
This sends the same POST request using fetch, but this version uses an async
function and the await
javascript expression to wait for the promises to return (instead of using the promise then()
method as above).
(async () => {
// POST request using fetch with async/await
const element = document.querySelector('#post-request-async-await .article-id');
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
const response = await fetch('https://reqres.in/api/articles', requestOptions);
const data = await response.json();
element.innerHTML = data.id;
})();
Example Fetch POST request at https://stackblitz.com/edit/fetch-http-post-request-examples?file=post-request-async-await.js
POST request using fetch with error handling
This sends a POST request with fetch to an invalid url on the api then writes the error message to the parent of the #post-request-error-handling .article-id
element and logs the error to the console.
The fetch()
function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok
property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);
. This approach means that both types of failed requests - network errors and HTTP errors - can be handled by a single catch()
block.
// POST request using fetch with error handling
const element = document.querySelector('#post-request-error-handling .article-id');
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
fetch('https://reqres.in/invalid-url', requestOptions)
.then(async response => {
const isJson = response.headers.get('content-type')?.includes('application/json');
const data = isJson && await response.json();
// check for error response
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
return Promise.reject(error);
}
element.innerHTML = data.id;
})
.catch(error => {
element.parentElement.innerHTML = `Error: ${error}`;
console.error('There was an error!', error);
});
Example Fetch POST request at https://stackblitz.com/edit/fetch-http-post-request-examples?file=post-request-error-handling.js
POST request using fetch with set HTTP headers
This sends the same POST request again using fetch with a couple of extra headers set, the HTTP Authorization
header and a custom header My-Custom-Header
.
// POST request using fetch with set headers
const element = document.querySelector('#post-request-set-headers .article-id');
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer my-token',
'My-Custom-Header': 'foobar'
},
body: JSON.stringify({ title: 'Fetch POST Request Example' })
};
fetch('https://reqres.in/api/articles', requestOptions)
.then(response => response.json())
.then(data => element.innerHTML = data.id);
Example Fetch POST request at https://stackblitz.com/edit/fetch-http-post-request-examples?file=post-request-set-headers.js
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some Fetch Help?
Search fiverr to find help quickly from experienced Fetch developers.