3

I am getting a 403 when I try to make a simple post request to a django view from within my react app. Here is my code:

views.py

@csrf_protect
def test_view():
    if (request.method == 'POST'):
        return HttpResponse(request.body)

Login.js (React component)

import Cookies from 'js-cookie';

//React constructor {

  test_view() {
      const csrftoken = Cookies.get('csrftoken');
      const config = {
        headers: {'HTTP_X_CSRFTOKEN': csrftoken},
      }
      axios.post('/prototype/hello/', {firstName: 'Fred'}, config)
        .then(res => {console.log("Test res: " + res.data)});
  }
//}

urls.py

    url(r'^hello', views.test_view, name='test-view'),

Is it possible that the 'js-cookie' library isn't working? I don't have {% csrf_token %} anywhere because I'm not using a django template other than index.html. Instead, I have the @csrf_protect decorator. I think that is what I'm supposed to do based on the docs.

1
  • you don't have to use csrf_protect if you didn't disable csrfmiddleware. and have you confirm that the cookies did get the csrf_token ? Commented Mar 30, 2017 at 1:47

1 Answer 1

10

Simply, set the below settings. Nothing else is required.

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.