This is a SERIES
FETCH API Part 1/4 (GET)
FETCH API Part 2/4 (POST)
FETCH API Part 3/4 (PUT)
FETCH API Part 4/4 (DELETE)
Using Fetch Api for POST request is way easier than you think.
SIMPLEST WAY TO USE FETCH FOR POST REQUEST
fetch(YOUR_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(YOUR_DATA_THAT_YOU_WANT_TO_POST)
})
What's happening here?
Here we are passing 2 arguments into the fetch function, 1st one is YOUR_URL, and 2nd one is an object describing about the request.
method: it's telling what type of request it is, here we described it as POST
Content-Type: it tells what kind of data we are sending. Here it is application/json that means we are sending json data. There are other options too, depending on what we are sending. But our main focus is this one.
body: it contains the actual data that we are sending. Here we have to stringify our javascript object if we want to send it. So we used JSON.stringify()
YOUR_DATA_THAT_YOU_WANT_TO_POST is a JavaScript object.
COMPLETE GUIDE FOR USING FETCH (POST)
PROMISE VERSION
const myDataObject = { name: `SilvenLEAF`, age: 19, isTeen: true};
fetch(YOUR_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(myDataObject)
})
.then(response => {
return response.json( )
})
.then(data =>
// this is the data we get after posting our data, do whatever you want with this data
console.log(data)
);
What's happening on the code?
We have the data inside the varriable myDataObject that we want to post. Now we passed the URL where we want to post, as the 1st argument on the fetch function. Then we passed an object as the 2nd argument, it describes more about the request.
Here we described the request as POST and also mentioned that our data that we will send is a json object using application/json. Then we described the data inside body property. It must be stringified. So we used JSON.stringify( ) to stringify our javascript object. then we are done. It posts our data to that url and then we get a response.
But as we already know that we can not use this response, we need to parse it first. (See my Prev blog describing it in details FETCH API PART 1/4 (GET)). After parsing it, we get the usable data on the data variable. Now that's how we make a POST request with FETCH so easily.
ASYNC AWAIT VERSION
//data that you want to send
const myDataObject = { name: `SilvenLEAF`, age: 19, isTeen: true };
const postData = async ( ) =>{
const response = await fetch(YOUR_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(myDataObject)
});
const data = await response.json( );
// now do whatever you want with the data
console.log(data);
};
postData( );
What's happening on the code?
The concept is totally same as the Promise version.
ONE NOTE: To use async and await, we define a function, then we call it. That's why use created a function named postData and then called it. Do NOT worry. I'll explain all about async and await on Nov 6th 2020.
Play with these codes to understand it better
ASYNC AWAIT VERSION
Copy-paste this code on your Browser console, (mine is Chrome) and hit enter.
//your data to send
const myDataObject = {
"userId": 1,
"id": 1,
"title": "The post of SilvenLEAF",
"completed": false
};
const postData = async ( ) =>{
const response = await fetch('https://jsonplaceholder.typicode.com/posts/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(myDataObject)
});
const data = await response.json( );
// now do whatever you want with the data
console.log(data);
};
postData( );
PROMISE VERSION
Copy-paste this code on your Browser console, (mine is Chrome) and hit enter.
//your data to send
const mySecondDataObject = {
"userId": 1,
"id": 1,
"title": "The post of SilvenLEAF",
"completed": false
};
fetch('https://jsonplaceholder.typicode.com/posts/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(mySecondDataObject)
})
.then(response => {
return response.json( )
})
.then(data =>
// this is the data we get after posting our data, do whatever you want with this data
console.log(data)
);
If you have any questions or If you are stuck
Feel free to reach out to me. You can also contact me on LinkedIN https://www.linkedin.com/in/silvenleaf/ or on Twitter (as @silvenleaf ).
If you wanna know more about me, this is my portfolio website SilvenLEAF.github.io
I'd LOVE to be your friend, feel FREE to reach out to me!!
NEXT BLOG is coming on 5th Nov, 2020
on FETCH API PART 3/4 (PUT) (Series)
Next Blogs DATE
Nov 6th 2020, async and await
Nov 8th 2020, how to use role-based auth system
Nov 10th 2020, Change CSS variables with JavaScript
Nov 12th, 14th, 16th 2020, Create login signup system with Passport (Series)
Nov 18th 2020, How to create Login with Google
Nov 20th 2020, How to create Login with Github
Nov 22th 2020, How to create Login with LinkedIn
Nov 24th 2020, How to create Login with Twitter
Nov 26th, 28th, 30th 2020, Password Reset Series (with Node.js and React)
If this blog was helpful to you,
PLEASE give a LIKE and share,
It'd mean a lot to me. Thanks
Prev Blog
FETCH API PART 1/4 (GET) (easiest explanation)
Top comments (0)