Welcome folks today in this blog post we will be looking on how to make a post request
to the JSONPlaceholder API Example in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 |
<form id="form"> <input type="text" id="name" placeholder="Enter Name"> <input type="text" id="body" placeholder="Enter body"> <input type="number" id="id" placeholder="Enter ID"> <input type="submit" value="Add Todo"> </form> |
As you can see in the above html code we have three
form fields which are allowing the user to enter the name,body
and id
of the todo
and then we have the button to submit the form to create the new todo. As you can see we have attached the attribute for the method which is POST because we are submitting this information and sending it to the JSONPlaceholder server to create the todo. And also we have attached the ID’s to the form and the input elements.
And now we will be getting the reference of the form
element using it’s id as shown below
1 |
let form = document.getElementById('form') |
And then we need to attach the submit
event listener to the form element and prevent the auto submission of the form using preventDefault()
method as shown below
1 2 3 4 |
form.addEventListener('submit', (e) => { e.preventDefault() }) |
And now we need to make the fetch api
post request to the jsonplaceholder api in order to create the new todo. We will get all the information entered by the user using the id
given as shown below
1 2 3 |
let name = document.getElementById('name').value let body = document.getElementById('body').value let id = document.getElementById('id').value |
And now we will be making the fetch api
post request as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fetch("https://jsonplaceholder.typicode.com/posts", { method: 'POST', body: JSON.stringify({ title: name, body: body, id: id }), headers: { "Content-Type": "application/json;charset=UTF-8" } }) .then((response) => { return response.json() }) .then((data) => { console.log(data) }) |
As you can see the fetch api expects the first argument
to be the url
endpoint where we will making the post request and in the second argument we are passing the options object where we are providing the method argument which is post and then we are passing the data inside the body parameter. And here we are converting to JSON using JSON.stringify() method. And here we are passing the three properties which is title,body and id parameter. And then we are also passing the headers object. So this returns the promise and we are handling this using the then
and catch syntax. And here we are converting the output
to json using json()
method.