[javascript] 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!

This question is related to javascript reactjs http axios http-delete

The answer is


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

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


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

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

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!


I had the same issue I solved it like that:

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

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

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

It worked for me.


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.


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


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.


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

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

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with reactjs tag:

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop react hooks useEffect() cleanup for only componentWillUnmount? How to use callback with useState hook in react Push method in React Hooks (useState)? React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component React hooks useState Array Can I set state inside a useEffect hook TypeScript and React - children type? Why do I keep getting Delete 'cr' [prettier/prettier]? How to use componentWillMount() in React Hooks? How to compare oldValues and newValues on React Hooks useEffect? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing Receiving "Attempted import error:" in react app How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once expected assignment or function call: no-unused-expressions ReactJS Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Support for the experimental syntax 'classProperties' isn't currently enabled How can I add raw data body to an axios request? Axios Delete request with body and headers? Enable CORS in fetch api Axios having CORS issue How to center a component in Material-UI and make it responsive? What exactly is the 'react-scripts start' command? how to download file in react js react button onClick redirect page Local package.json exists, but node_modules missing Upgrading React version and it's dependencies by reading package.json What is {this.props.children} and when you should use it? How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps Adding an .env file to React Project React : difference between <Route exact path="/" /> and <Route path="/" /> You should not use <Link> outside a <Router> ReactJS: Maximum update depth exceeded error Functions are not valid as a React child. This may happen if you return a Component instead of from render where is create-react-app webpack config and files? React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

Questions with http tag:

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe How to read values from the querystring with ASP.NET Core? How to correctly set Http Request Header in Angular 2 http post - how to send Authorization header? Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8 Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint Send FormData with other field in AngularJS CORS with POSTMAN Send multipart/form-data files with angular using $http Response to preflight request doesn't pass access control check How to catch exception correctly from http.request()? Setting query string using Fetch GET request How to create cross-domain request? Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding How to pass url arguments (query string) to a HTTP request on Angular? How to send an HTTP request with a header parameter? How to send a POST request from node.js Express? Use .htaccess to redirect HTTP to HTTPs What is the "Upgrade-Insecure-Requests" HTTP header? Send POST parameters with MultipartFormData using Alamofire, in iOS Swift How to make HTTP Post request with JSON body in Swift What is the difference between PUT, POST and PATCH? Difference between request.getSession() and request.getSession(true) Go doing a GET request and building the Querystring javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer Correct way to set Bearer token with CURL Why is an OPTIONS request sent and can I disable it? How to get http headers in flask? Understanding Chrome network log "Stalled" state REST API - Bulk Create or Update in single request What is the difference between HTTP 1.1 and HTTP 2.0? Use of PUT vs PATCH methods in REST API real life scenarios How does OkHttp get Json string? Returning http 200 OK with error within response body POST request with a simple string in body with Alamofire REST API error code 500 handling Correct way of getting Client's IP Addresses from http.Request Proper way to set response status and JSON content in a REST API made with nodejs and express How to define the basic HTTP authentication using cURL correctly? How to get response body using HttpURLConnection, when code other than 2xx is returned? wget: unable to resolve host address `http'

Questions with axios tag:

How to post query parameters with Axios? Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check How can I add raw data body to an axios request? Axios Delete request with body and headers? Axios having CORS issue Axios handling errors Returning data from Axios API axios post request to send form data Change the default base url for axios Access Control Origin Header error using Axios in React Web throwing error in Chrome How to set header and options in axios? Passing headers with axios POST request How to send authorization header with axios How to send Basic Auth with axios Put request with simple string as request body How to overcome the CORS issue in ReactJS Attach Authorization header for all axios requests How to post a file from a form with Axios Make Axios send cookies in its requests automatically How to download files using axios How do I set multipart in axios with react? Using Axios GET with Authorization Header in React-Native App 'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app) Sending the bearer token with axios Axios get in url works but with second parameter as object it doesn't How can I get the status code from an http error in Axios? how to cancel/abort ajax request in axios Axios get access to response header fields

Questions with http-delete tag:

Axios Delete request with body and headers? Javascript: Fetch DELETE and PUT requests Body of Http.DELETE request in Angular2 What REST PUT/POST/DELETE calls should return by a convention? How to send PUT, DELETE HTTP request in HttpURLConnection?