【发布时间】:2021-03-29 13:42:48
【问题描述】:
我正在尝试构建一个通过 API 连接前后的 CRUD 应用程序。我已经让应用程序与 vanilla JS 一起工作,但我想用 Vue.js 构建它,使用 Axios 来处理 API。该应用程序与 vanilla JS fetch() 一起使用,当我使用 Axios 与 Postman 进行测试时,它也可以使用。
但是我在 Vue 中使用 Axios 做错了,我认为这是我如何使用“数据”收集要删除的 id 的问题。或者可能是“标题”的问题。抛出的唯一错误来自我的后端 PHP,如果 mysqli_query(connection and sql delete request) 不满足,则返回 false。控制台显示一般状态 200 但数据状态 0。
这是正常工作的原版 JS:
//Function to send form data
deleteForm.addEventListener('submit', function(e){
//Prevent page from reloading when the form is submitted
e.preventDefault();
//Collect the form data
var deleteIDVar = document.getElementById('reviewCakeId').value;
//Prepare the header
var myHeaders = new Headers();
myHeaders.append("Access-Control-Request-Method", "POST");
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
//Prepare the body with data from the form
var urlencoded = new URLSearchParams();
urlencoded.append("ID", deleteIDVar);
//Prepare the attributes of the post request
var requestOptions = {
method: 'DELETE',
headers: myHeaders,
body: urlencoded
};
//Make the post request with fetch
fetch("https://*******/delete.php", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.then(confirm => {
document.getElementById("confirm").innerHTML = "Deleted!";
})
.catch(error => console.log('error', error));
console.log(requestOptions);
});
这是来自 Postman 的 Axios,它也可以正常工作:
var axios = require('axios');
var qs = require('qs');
var data = qs.stringify({
'ID': '58'
});
var config = {
method: 'delete',
url: 'https://******/delete.php',
headers: {
'Access-Control-Request-Method': 'POST',
'Content-Type': 'application/x-www-form-urlencoded'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
这是我在 Vue 和 Axios 中得到的,它不起作用:
<script>
import axios from 'axios';
export default {
data(){
return{
configDelete: {
method: 'delete',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'https://********/delete.php',
data: {id: 58}
}
}
},
methods:{
sendDeleteRequest(){
axios(this.configDelete)
.then(response => (this.cakes = response))
.then(response => console.log(response));
}
}
};
我知道我没有像 Postman 示例那样使用 qs.stringify。我查了一下它是什么并读到它不需要,不确定我是否正确。我也知道我不像邮递员版本那样包括'Access-Control-Request-Method': 'POST', 。我试过了,控制台抛出错误Refused to set unsafe header "Access-Control-Request-Method"。当我删除它时,状态返回 200 但数据的状态为 0 并且我的 PHP 错误消息。
我在这里查看了答案、youtube 教程、Axios github 页面、Vue 官方论坛和大量较小的文章,似乎他们都像这样使用 Axios axios.delete(url, {params: {id}}) ... 。我已经尝试过了,但如果有的话,得到了相同的响应。他们中很少有人详细介绍“数据”或“标题”。我使用的方法 axios(config)... 来自 Postman,如果可能的话,我更愿意坚持使用它。
我已经用 Axios 在 Vue 中构建了读取部分,它工作正常,所以我知道连接是正确的。任何帮助表示赞赏。
***** 已添加 ******
关于我的 PHP 后端有一些 cmets,所以我将在此处添加:
<?php
//Open CORS security feature
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE');
//Access the database
include_once 'config.php';
//Check for incoming request
if($_SERVER['REQUEST_METHOD'] == "DELETE"){
// Assign incoming posts to variables and sanitise them.
$rawData = parse_str(file_get_contents('php://input'));
$reviewCakeId = isset($ID) ? mysqli_real_escape_string($conn, $ID) : "";
// Update the database
$sql = "DELETE FROM `reviewtable` WHERE `id` = $reviewCakeId;";
$post_data_query = mysqli_query($conn, $sql);
if($post_data_query){
$json = array("status" => 1, "Success" => "Review has been deleted successfully!");
}
else{
$json = array("status" => 0, "Error" => "Error deleting! Please try again!");
}
}
else{
$json = array("status" => 0, "Info" => "Request method not accepted!");
}
@mysqli_close($conn);
echo json_encode($json);
【问题讨论】:
-
您应该知道您的 PHP 期望接收 POST 有效负载(JSON 格式)或 GET 查询参数。然后你就会知道在 Axios 中要发送什么。假设您的 PHP 代码需要一个带有 JSON 编码负载的 POST,那么您将调用 Axios,例如
axios.delete('/api/whatever/delete.php', {id: product_to_delete}) -
您的 PHP 后端可能希望以 JSON 格式提供数据。您正在提供一个香草 javascript 对象。您是否尝试过使用
data: JSON.stringify({id: 58})?我怀疑这与您的邮递员代码示例中的qs.stringify相同。 -
谢谢 Ivo 和 Aside。伊沃:我不确定你的意思。 PHP标头是“('Access-Control-Allow-Methods:DELETE')”,所以它需要删除方法,这是你的意思吗?另外,我尝试了 JSON.stringify 就像你展示的那样,它返回了和以前一样的错误,没有任何改变。
标签: javascript vue.js axios crud vuejs3