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

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

headers: {
  'Authorization': ...
}

而身体是由

var payload = {
    "username": ..
}

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

我一直想这样发送

axios.delete(URL, payload, header);

甚至

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

但似乎什么都不管用……

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


当前回答

下面是使用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键来正确设置查询参数 删除带有主体的请求需要将其设置在数据键下

其他回答

我也遇到过同样的问题…… 我通过创建一个自定义axios实例解决了这个问题。并使用它来进行身份验证删除请求..

const token = localStorage.getItem('token');
const request = axios.create({
        headers: {
            Authorization: token
        }
    });

await request.delete('<your route>, { data: { <your data> }});

要通过axios发送带有一些头的HTTP DELETE,我已经这样做了:

  const deleteUrl = "http//foo.bar.baz";
  const httpReqHeaders = {
    'Authorization': token,
    'Content-Type': 'application/json'
  };
  // check the structure here: https://github.com/axios/axios#request-config
  const axiosConfigObject = {headers: httpReqHeaders}; 

  axios.delete(deleteUrl, axiosConfigObject);

不同HTTP动词(GET, POST, PUT, DELETE)的axios语法很棘手,因为有时第二个参数应该是HTTP正文,而在其他时候(当它可能不需要时),您只需将头信息作为第二个参数传递。

然而,假设你需要发送一个没有HTTP正文的HTTP POST请求,那么你需要传递undefined作为第二个参数。

请记住,根据配置对象(https://github.com/axios/axios#request-config)的定义,在调用axios.delete时,仍然可以通过data字段在HTTP调用中传递HTTP主体,但是对于HTTP DELETE谓词,它将被忽略。

第二个参数有时是HTTP主体,有时是axios的整个配置对象,这种混淆是由于HTTP规则是如何实现的。有时HTTP调用被认为是有效的,并不需要HTTP主体。

所以在尝试了几次之后,我发现它起作用了。

请按顺序做,这很重要,否则不行

axios.delete(URL, {
  headers: {
    Authorization: authorizationToken
  },
  data: {
    source: source
  }
});

对于删除,您将需要按照以下步骤进行操作

axios.delete("/<your endpoint>", { data:<"payload object">})

这对我很管用。

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

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