Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

403 error code when using axios.post to Django endpoint in React app

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.

like image 214
Elise Rodrigues Avatar asked Feb 26 '26 12:02

Elise Rodrigues


1 Answers

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

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';
like image 152
Vishal Avatar answered Mar 01 '26 03:03

Vishal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!