我已经是习惯 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/