Day 91 : #100DaysofCode - Made a POST and PATCH request using FETCH

sincerelybrittany profile image Brittany ・2 min read

I did not feel like writing my blog post yesterday but I did code! I made a POST and Patch request using FETCH. How did I do it? Well, I followed the lab provided by my bootcamp.

First I made a GET request to get all of the items in my database and append them to the page:

function getAllToys(){
  return fetch("http://localhost:3000/toys")
  .then(function(response) {
     return response.json();
   .then(function(object) {
    //  console.log(object);
     const characters = object
     characters.forEach(character =>{ 
      const collection = document.querySelector('#toy-collection')  
      // console.log(character)
      let div = document.createElement('div');
      div.className = "card"
      div.innerHTML = `<h2>${character.name}</h2><br>
      <img src=${character.image} class="toy-avatar" /><br><p>Likes: ${character.likes}</p><button class="like-btn">Like <3</button><br>`
      // console.log(collection, "this is collection")
    //  div.append(object.name)
    //  document.body.innerHTML = object.id

I called the getAllToys() function when the DOMContentLoaded:

document.addEventListener("DOMContentLoaded", () => {

Then I wanted to be able to add to my database so I created form and added an event listener to the form that would use the input given in the form and use it in a function that I named submitData.

  const form = document.querySelector("form.add-toy-form");
  form.addEventListener("submit", (e) => {
    let input = document.querySelector('input.input-text')
    let image = document.querySelector('input.input-text-image')
    submitData(input.value, image.value)


The submitData function takes two arguments, which is the name and image that the user inputted into the form. Then I created a variable named configObj for the post request that must be passed into the fetch request.

function submitData(name, image){

  let formData = {
      name: name,
      image: image,

  let configObj = {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
          body: JSON.stringify(formData)

       return fetch("http://localhost:3000/toys", configObj)
       .then(function(response) {
          return response.json();
        .then(function(object) {
        .catch(function(error) {


Then I made the post request and if there are any errors, I console.log the error message.

For a better understanding on making POST request using fetch, feel free to checkout this youtube video:

As always, thanks for reading!


Posted on by:

sincerelybrittany profile



Developer | Software Engineer πŸ‘©πŸΎβ€πŸ’» | Determined | Music & Dance | Completed #100DaysofCode | #WomenWhoCode |MLH Fellow


Editor guide