Axios Delete request with body and headers?

2020-01-31 00:37发布

问题:

I'm using Axios while programing in ReactJS and I pretend to send a DELETE request to my server.

To do so I need the headers:

headers: {
  'Authorization': ...
}

and the body is composed of

var payload = {
    "username": ..
}

I've been searching in the inter webs and only found that the DELETE method requires a "param" and accepts no "data".

I've been trying to send it like so:

axios.delete(URL, payload, header);

or even

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

But nothing seems to work...

Can someone tell me if its possible (I presume it is) to send a DELETE request with both headers and body and how to do so ?

Thank you in advance!

回答1:

So after a number of tries, I found it working.

Please follow the order sequence it's very important else it won't work

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


回答2:

axiox.delete does support a request body. It accepts two parameters: url and optional config. You can use config.data to set the response body and headers as follows:

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

See Here - https://github.com/axios/axios/issues/897



回答3:

Here is a brief summary of the formats required to send various http verbs with axios:

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

Key take aways

  • get requests optionally need a params key to properly set query parameters
  • delete requests with a body need it to be set under a data key


回答4:

axios.delete is passed a url and an optional configuration.

axios.delete(url[, config])

The fields available to the configuration can include the headers.

This makes it so that the API call can be written as:

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

axios.delete('https://foo.svc/resource', {headers, data})


回答5:

I had the same issue I solved it like that:

axios.delete(url, {data:{username:"user", password:"pass"}, headers:{Authorization: "token"}})


回答6:

To send an HTTP DELETE with some headers via axios I've done this:

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

The axios syntax for different HTTP verbs (GET, POST, PUT, DELETE) is tricky because sometimes the 2nd parameter is supposed to be the HTTP body, some other times (when it might not be needed) you just pass the headers as the 2nd parameter.

However let's say you need to send an HTTP POST request without an HTTP body, then you need to pass undefined as the 2nd parameter.

Bare in mind that according to the definition of the configuration object (https://github.com/axios/axios#request-config) you can still pass an HTTP body in the HTTP call via the data field when calling axios.delete, however for the HTTP DELETE verb it will be ignored.

This confusion between the 2nd parameter being sometimes the HTTP body and some other time the whole config object for axios is due to how the HTTP rules have been implemented. Sometimes an HTTP body is not needed for an HTTP call to be considered valid.



回答7:

I encountered the same problem... I solved it by creating a custom axios instance. and using that to make a authenticated delete request..

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

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


回答8:

For Delete, you will need to do as per the following

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

It worked for me.