vue.js - 如何在 Vue 中成功发出 HTTP PUT 请求?

标签 vue.js put

我已经是习惯 Vue CLI 的第 4 天了,我正在尝试发出 HTTP put 请求,但真的不知道从哪里开始。我将其设置为当用户单击特定产品上的喜欢按钮时,它会向实际产品添加喜欢,但我希望将其保存到我的数据库中。任何帮助将不胜感激,但也知道我仍在学习并且对这个 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
      })
    })
  }
}

最佳答案

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

关于vue.js - 如何在 Vue 中成功发出 HTTP PUT 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55443653/

相关文章:

javascript - Vue 单文件组件无法使用 webpack 正确加载

javascript - 使用 Vue Cli 3 链接到字体

javascript - 以一定数量的字符隐藏文章的其余部分

python - 使用 Python 将请求发送到 REST API

html - HTML元素在Tailwind CSS中的位置

laravel - 如何索引没有公共(public)链接的谷歌动态页面?

python urllib2 发布请求

java - Jmeter Http 代理服务器抛出 java.net.URISyntaxException : Illegal character in query at index error

rest - 如果资源不存在,HTTP PUT 是否应该创建资源?

java - 使用 Rest 模板对外部网站进行 PUT 调用