Axios Delete request with body and headers?

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!

15 Answers

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

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 -

1

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
10

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(' {headers, data})
3

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:

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

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

It worked for me.

I had the same issue I solved it like that:

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

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!

1

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

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.

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: 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 () 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.

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

Thanks to:

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

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(` bayst) .then((response) => response.data) .catch((error) => { throw error.response.data; });

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like