如何在Vue中成功发出HTTP PUT请求?

时间:2019-03-31 17:39:39

标签: vue.js put

我已经习惯了Vue CLI的第4天,正在尝试发出HTTP放置请求,但真的不知道从哪里开始。我将其设置为当用户单击特定产品上的“赞”按钮时,它将在实际产品中添加“赞”,但是我希望将其保存到我的数据库中。任何帮助将不胜感激,但也知道我仍在学习并且对该JavaScript库非常陌生。我也在使用Vue Resource发出此PUT请求。

单击“喜欢”按钮时,我可以确认它为该特定产品添加了喜欢,并在该特定产品上显示了喜欢的数量。只是不知道如何正确地将其发送到数据库。

这是我用于PUT请求的代码。我是否需要标题和

    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);
    }
  }

更新代码:

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
      })
    })
  }
}

3 个答案:

答案 0 :(得分:1)

您可以使用浏览器的本机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!'
  })
})

答案 1 :(得分:1)

在Vue资源中,您可以发出如下所示的HTTP PUT请求

this.$http.put('/someUrl', {your request body}).then(response => {
  this.product.likes = response.body.likes; // update your data from the response
}, error => {
   // error callback
});

您可以查看Vue Resource docs以获得更多详细信息。

另外,我认为您不应该手动增加产品的赞数,如果响应中包含更新的产品喜欢数,则可以从请求响应中进行设置,因为也许产品喜欢度没有在服务器上更新。

答案 2 :(得分:0)

首先,您需要确保可以直接发送PUT请求,而无需使用Vue。您可以使用Curl或Postman

第二,当您从Vue发送请求时,请检查浏览器开发人员工具( F12 )中的“网络”标签。请求是否正确发送?服务器返回错误了吗?

接下来,检查CORS问题。您的请求很有可能被拒绝,因为它是从localhost发送到您的服务器的,并且您没有允许正确的CORS访问。