简体   繁体   中英

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:

在此处输入图像描述

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM