DEV Community

eliastooloee
eliastooloee

Posted on

Post Requests in Javascript

During the most recent code challenge at Flatiron School's Seattle Campus, it became clear that many students lack a clear understanding of the format for POST and PATCH requests. Let's walk through a simple post request to find out exactly how it works, line by line and step by step. We'll be using an example from one of our in class pair programming exercises. This POST request is to create a new Pokemon in our database.

function addPokemon(trainer) {
fetch(`http://localhost:3000/pokemons/`, {
method: "POST",
headers: { "Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify({trainer_id: trainer.id})
})
.then(res => res.json())
.then(data => {
listPokemon(data)
})
}

First we see a 'trainer' being passed into the function. This is because we want to associate the Pokemon we are creating with the trainer who has captured it.

Next we see a fetch request. This specifies where our POST request will go. We need the result of this fetch before we can proceed with the rest of our request.

Next we see the method "POST". This specifies the type of request we are making.

We then come to headers. The headers job is to tell the server what type of data to accept and what to send back. In this case we're telling the server that we will be sending JSON (Javascript Object Notation) and expect to receive JSON back.

The next piece is the line that says "JSON.stringify". This line converts the object we are sending into a JSON string.

Our Post request ends at at this point. In the following lines we are handling the data we get back. We first pass it to the .json function, will receive it as a promise with JSON content.

Top comments (0)