我在ReactJS中编程时使用Axios,我假装向服务器发送DELETE请求。

要做到这一点,我需要头文件:

headers: {
  'Authorization': ...
}

而身体是由

var payload = {
    "username": ..
}

我一直在网上搜索,只发现DELETE方法需要一个“参数”,不接受“数据”。

我一直想这样发送

axios.delete(URL, payload, header);

甚至

axios.delete(URL, {params: payload}, header);

但似乎什么都不管用……

有人能告诉我,如果这是可能的(我假设是)发送一个删除请求与头部和主体,以及如何这样做?


当前回答

与axios无关,但可能帮助人们解决他们正在寻找的问题。PHP在执行delete调用时不解析post数据。Axios delete可以发送带有请求的主体内容。 例子:

//post example
let url = 'http://local.test/test/test.php';
let formData = new FormData();
formData.append('asdf', 'asdf');
formData.append('test', 'test');

axios({
    url: url,
    method: 'post',
    data: formData,
}).then(function (response) {
    console.log(response);
})

result: $_POST Array
(
    [asdf] => asdf
    [test] => test
)


// delete example
axios({
    url: url,
    method: 'delete',
    data: formData,
}).then(function (response) {
    console.log(response);
})

result: $_POST Array
(        
)

要在PHP中获得删除调用的post数据,请使用:

file_get_contents('php://input'); 

其他回答

我找到了一个有效的方法:

axios
      .delete(URL, {
        params: { id: 'IDDataBase'},
        headers: {
          token: 'TOKEN',
        },
      }) 
      .then(function (response) {
        
      })
      .catch(function (error) {
        console.log(error);
      });

我希望这对你也有用。

我尝试了以上所有的方法,但对我都不起作用。我最终只是使用PUT(灵感来自这里),只是改变了我的服务器端逻辑,对这个url调用执行删除。(django rest框架函数重写)。

e.g.

.put(`http://127.0.0.1:8006/api/updatetoken/20`, bayst)
      .then((response) => response.data)
      .catch((error) => { throw error.response.data; });

与axios无关,但可能帮助人们解决他们正在寻找的问题。PHP在执行delete调用时不解析post数据。Axios delete可以发送带有请求的主体内容。 例子:

//post example
let url = 'http://local.test/test/test.php';
let formData = new FormData();
formData.append('asdf', 'asdf');
formData.append('test', 'test');

axios({
    url: url,
    method: 'post',
    data: formData,
}).then(function (response) {
    console.log(response);
})

result: $_POST Array
(
    [asdf] => asdf
    [test] => test
)


// delete example
axios({
    url: url,
    method: 'delete',
    data: formData,
}).then(function (response) {
    console.log(response);
})

result: $_POST Array
(        
)

要在PHP中获得删除调用的post数据,请使用:

file_get_contents('php://input'); 
axios.post('/myentity/839', {
  _method: 'DELETE'
})
.then( response => {
  //handle success
})
.catch( error => {
   //handle failure
});

感谢: https://www.mikehealy.com.au/deleting-with-axios-and-laravel/

Axios DELETE请求支持与POST请求类似的功能,但格式不同。

DELETE请求有效负载示例代码:

axios.delete(url, { data: { hello: "world" }, headers: { "Authorization": "Bearer_token_here" } });

POST请求有效负载示例代码:

axios.post(url, { hello: "world" }, { headers: { "Authorization": "Bearer_token_here" } });

注意{hello: "world"}以不同的方式配置,但都执行相同的功能。