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

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

headers: {
  'Authorization': ...
}

而身体是由

var payload = {
    "username": ..
}

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

我一直想这样发送

axios.delete(URL, payload, header);

甚至

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

但似乎什么都不管用……

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


当前回答

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})

我尝试了以上所有的方法,但对我都不起作用。我最终只是使用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; });

此代码是由post man生成的,它可以很好地处理带有body的删除API请求。

var data = JSON.stringify({"profile":"false","cover":"true"});

var config = {
  method: 'delete',
  url: 'https://api.fox.com/dev/user/image',
  headers: { 
    'Authorization': 'Bearer token', 
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});
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发送各种http动词所需的格式的简要总结:

GET: Two ways First method axios.get('/user?ID=12345') .then(function (response) { // Do something }) Second method axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { // Do something }) The two above are equivalent. Observe the params keyword in the second method. POST and PATCH axios.post('any-url', payload).then( // payload is the body of the request // Do something ) axios.patch('any-url', payload).then( // payload is the body of the request // Do something ) DELETE axios.delete('url', { data: payload }).then( // Observe the data keyword this time. Very important // payload is the request body // Do something )

关键要点

获取请求可选地需要一个params键来正确设置查询参数 删除带有主体的请求需要将其设置在数据键下