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!
Here is a brief summary of the formats required to send various http verbs with axios:
GET
: Two waysThe two above are equivalent. Observe the
params
keyword in the second methodPOST
andPATCH
DELETE
Key take aways
get
requests optionally need aparams
key to properly set query parametersdelete
requests with a body need it to be set under adata
keyI had the same issue I solved it like that:
axios.delete is passed a url and an optional configuration.
The fields available to the configuration can include the headers.
This makes it so that the API call can be written as:
axiox.delete
does support a request body. It accepts two parameters: url and optional config. You can useconfig.data
to set the response body and headers as follows:See Here - https://github.com/axios/axios/issues/897
To send an HTTP DELETE with some headers via
axios
I've done this: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 callingaxios.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 foraxios
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.I encountered the same problem... I solved it by creating a custom axios instance. and using that to make a authenticated delete request..