Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I successfully make an HTTP PUT request in Vue?

Tags:

put

vue.js

I am on my 4th day in getting used to Vue CLI and am trying to make an HTTP put request, but really don't know where to start. I have it setup to where when a user clicks a like button on a specific product, it will add a like to the actual product, but I want it to save to my database. Any help would be much appreciated, but also know that I am still learning and quite new to this JavaScript Library. I am also using Vue Resource to make this PUT request.

When I click the like button, I can confirm that it adds a like to that specific product and displays on that specific products's amount of likes. Just have no idea how to properly send it to the database.

Here is my code for the PUT request. Do I need headers and

    methods: {
      updateLikes(product){
        //make a put request to the backend to update the amount of likes on
        //the specific product when the user click like button
        product.likes = product.likes + 1
        this.$http.put(`https://tap-on-it-exercise-backend.herokuapp.com/products/${product.likes}`, {
          //send updated likes for the product to the backend

        })
        //close the modal after user like
        this.modalShow = false
      console.log(product.likes);
    }
  }

update code:

methods: {
  updateLikes(product){

    let newProductLikes = product.likes + 1

    //make a put request to the backend to update the amount of likes on
    //the specific product when the user click like button

    console.log('new', newProductLikes);

    fetch(`https://tap-on-it-exercise-backend.herokuapp.com/products/${product.likes}`, {
      method: 'PUT',
      mode: "cors",
      cache: "no-cache",
      credentials: "same-origin",
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        // send updated like to the server
        likes: newProductLikes
      })
    })
  }
}
like image 462
Tyler Avatar asked Dec 08 '25 09:12

Tyler


1 Answers

You can use the browser's native fetch() API.

fetch(`https://tap-on-it-exercise-backend.herokuapp.com/products/${product.likes}`, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    // data you intend to send as JSON to the server
    whatever: 'ding!'
  })
})
like image 142
Soviut Avatar answered Dec 11 '25 02:12

Soviut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!