0

I am using React + Django and trying to make a post request using axios but it is failing due to csrf. I have tried all the answers posted on internet to similar problem but none of them are working for some weird reason.

//Django View
def createUser(request):
    username = request.POST['username']
    email = request.POST['email']
    resp = {
      'username' : username,
      'email' : email
    }
    return JsonResponse(resp)



//Axios Post
 axios.post('http://localhost:8000/api/createUser/',{
       username : 'xyz',
       email : 'xyz@gmail.com'
    },
    {
       headers: {
         Content-Type': 'application/json',
       }
    });

tried adding defaults

axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";

but still getting csrf failed. I know i can do @csrf_exempt on the view but i want to keep the csrf check.

Andro
  • 381
  • 1
  • 4
  • 9
  • Are you sure its `X-CSRFTOKEN` and not `X-CSRF-TOKEN` – Advaith Jun 01 '18 at 16:32
  • @Advaith i followed this SO answer and it says X-CSRFTOKEN https://stackoverflow.com/questions/39254562/csrf-with-django-reactredux-using-axios?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Andro Jun 01 '18 at 18:46

1 Answers1

0

Along with the X-CSRFToken header, also include the cookies in the axios request using withCredentials: true

My original answer

Anubhav Das
  • 940
  • 1
  • 11
  • 16