我在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无关,但可能帮助人们解决他们正在寻找的问题。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和一个可选配置。这是……

axios.delete(url: string, config?: AxiosRequestConfig | undefined)

您可以通过以下方法设置删除请求的响应体:

let config = { 
    headers: {
        Authorization: authToken
    },
    data: { //! Take note of the `data` keyword. This is the request body.
        key: value,
        ... //! more `key: value` pairs as desired.
    } 
}

axios.delete(url, config)

我希望这能帮助到一些人!

delete同时支持请求正文和请求头。

它接受两个参数:url和可选配置。您可以使用配置。设置请求正文和请求头的数据如下:

axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } });

请看这里- https://github.com/axios/axios/issues/897

delete传递一个url和一个可选配置。

axios.delete (url(配置)

配置可用的字段可以包括头信息。

这使得API调用可以写成:

const headers = {
  'Authorization': 'Bearer paperboy'
}
const data = {
  foo: 'bar'
}

axios.delete('https://foo.svc/resource', {headers, data})
axios.post('/myentity/839', {
  _method: 'DELETE'
})
.then( response => {
  //handle success
})
.catch( error => {
   //handle failure
});

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