Django Rest Framework says CSRF verification failed despite CSRF token is included in axios POST header

I have following react code to make call to django rest framework API:

import Cookies from 'js-cookie';
import axios from "axios";

async downloadVideowiseCSV (fromDate, toDate) {
        var url = '/stat/getStats/';
        const axiosInstance = axios.create(); 

        try {
            const response = await axiosInstance.post(url,
                {
                    data: {
                        'format': 'json'
                    },
                    header: {
                        'X-CSRFToken': Cookies.get('csrftoken')
                    }
                }
            )
        //...
}

When this method gets called, the corresponding request fails with CSRF verification:

enter image description here

However when I check the payload of the request, I could see that X-CSRFTOken is indeed populated:

enter image description here

Then whats going wrong here?

The problem is in your axios request, it's not correct to send the header in the body of the HTTP request.

The following should be a valid axios request which separates the data from the options ex:

const config = {
  headers: { 'X-CSRFToken': Cookies.get('csrftoken') },
};

const data = {format: 'json'}

axios.post('http://YOUR_URL', data, config)
  .then((response) => {
  console.log(response.data);
});
Back to Top