Axios Delete request with body and headers?

JavascriptReactjsHttpAxiosHttp Delete

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

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

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

For those who tried everything above and still don't see the payload with the request - make sure you have:

"axios": "^0.21.1" (not 0.20.0)

Then, the above solutions work

axios.delete("URL", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data: {
        var1: "var1",
        var2: "var2"
      },
    })

You can access the payload with

req.body.var1, req.body.var2

Here's the issue:

https://github.com/axios/axios/issues/3335

Solution 6 - Javascript

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

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

It worked for me.

Solution 7 - Javascript

I had the same issue I solved it like that:

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

Solution 8 - Javascript

Actually, axios.delete supports a request body.
It accepts two parameters: a URL and an optional config. That is...

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

You can do the following to set the response body for the delete request:

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)

I hope this helps someone!

Solution 9 - Javascript

If we have:

myData = { field1: val1, field2: val2 }

We could transform the data (JSON) into a string then send it, as a parameter, toward the backend:

axios.delete("http://localhost:[YOUR PORT]/api/delete/" + JSON.stringify(myData), 
     { headers: { 'authorization': localStorage.getItem('token') } }
 )

In the server side, we get our object back:

app.delete("/api/delete/:dataFromFrontEnd", requireAuth, (req, res) => {
    // we could get our object back:
    const myData = JSON.parse(req.params.dataFromFrontEnd)
 })

Note: the answer from "x4wiz" on Feb 14 at 15:49 is more accurate to the question than mine! My solution is without the "body" (it could be helpful in some situation...)

Update: my solution is NOT working when the object has the weight of 540 Bytes (15*UUIDv4) and more (please, check the documentation for the exact value). The solution of "x4wiz" (and many others above) is way better. So, why not delete my answer? Because, it works, but mostly, it brings me most of my Stackoverflow's reputation ;-)

Solution 10 - Javascript

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.

Solution 11 - Javascript

i found a way that's works:

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

I hope this work for you too.

Solution 12 - Javascript

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

Thanks to: https://www.mikehealy.com.au/deleting-with-axios-and-laravel/

Solution 13 - Javascript

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

Solution 14 - Javascript

I tried all of the above which did not work for me. I ended up just going with PUT (inspiration found here) and just changed my server side logic to perform a delete on this url call. (django rest framework function override).

e.g.

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

Solution 15 - Javascript

Not realated to axios but might help people tackle the problem they are looking for. PHP doesn't parse post data when preforming a delete call. Axios delete can send body content with a request. example:

//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
(        
)

to get post data on delete call in php use:

file_get_contents('php://input'); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsfourhundredView Question on Stackoverflow
Solution 1 - Javascriptvishu2124View Answer on Stackoverflow
Solution 2 - Javascripttarzen chughView Answer on Stackoverflow
Solution 3 - JavascriptVan_PaitinView Answer on Stackoverflow
Solution 4 - JavascriptOluwafemi SuleView Answer on Stackoverflow
Solution 5 - Javascriptx4wizView Answer on Stackoverflow
Solution 6 - JavascriptHemantkumar GaikwadView Answer on Stackoverflow
Solution 7 - JavascriptronaraView Answer on Stackoverflow
Solution 8 - JavascriptThunderBirdView Answer on Stackoverflow
Solution 9 - Javascriptuser14348713View Answer on Stackoverflow
Solution 10 - JavascriptTPPZView Answer on Stackoverflow
Solution 11 - JavascriptDamian GuilisastiView Answer on Stackoverflow
Solution 12 - JavascriptSyed MobarakView Answer on Stackoverflow
Solution 13 - Javascriptjimijuu omastarView Answer on Stackoverflow
Solution 14 - JavascriptJoshView Answer on Stackoverflow
Solution 15 - JavascriptSjaak WishView Answer on Stackoverflow