首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除请求接口Axios Vue.js

删除请求接口Axios Vue.js
EN

Stack Overflow用户
提问于 2021-03-29 21:42:48
回答 1查看 701关注 0票数 1

我正在尝试建立一个通过API连接前后的CRUD应用程序。我已经让应用程序与香草JS一起工作,但我想用Vue.js构建它,使用Axios来处理API。这个应用程序可以使用vanilla JS fetch(),当我使用Axios测试Postman时,它也可以使用。

但是我在Vue中使用Axios做了一些错误的事情,我认为这是一个问题,我如何使用"data“来收集要删除的id。或者可能是“头”的问题。抛出的唯一错误来自我的后端PHP,如果mysqli_query(连接和sql delete请求)得不到满足,它将返回false。控制台显示常规状态200,但数据状态为0。

下面是工作正常的普通JS:

代码语言:javascript
复制
   //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,它也工作正常:

代码语言:javascript
复制
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上得到的,它不工作:

代码语言:javascript
复制
<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));
      }
   }
};

我知道我没有像邮递员示例那样使用qs.stringify。我查了查它是什么,发现它不是必需的,不确定我是否正确。我也知道我没有像邮递员版本那样包括'Access-Control-Request-Method': 'POST',。我试过了,console抛出了错误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后端的评论,所以我在这里补充一下:

代码语言:javascript
复制
<?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);
EN

回答 1

Stack Overflow用户

发布于 2021-07-15 18:26:18

我不会深入细节,但总的来说,问题(现在已经解决)在于Javascript fetch()方法和Axios之间的差异。

fetch()似乎不需要PHP来解码JSON、GET、POST、PUT和DELETE请求。但是,Axios确实需要PHP来解码JSON。

更新PHP以解码传入请求后,使用Axios的API请求似乎没有问题。整个CRUD系统现在工作正常,如下所示:(http://cake-creator.s3-website.eu-west-2.amazonaws.com/)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66855321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档