1

Yo guys ,

I'm doing a frontend react that call a Django api. I ve got a big problem : I want to call a Django API with reactjs but the API need a csrf and I have no idea how i could get that csrf, after looking on internet, i saw some people using function other telling that the django api need a route that retrun the token. I'm totally lost.

my discord if needed Wadi #1916

1 Answer 1

1

Here's a good post on how to do it.

The highlights are:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

Then you can use it with a fetch:

  fetch(url, {
    credentials: 'include',
    method: 'POST',
    mode: 'same-origin',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRFToken': getCookie('csrftoken')
    },
    body: {}
   })
  }

Apparently using axios is much easier:

import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

You may also need to ensure that the csrf token is getting sent to the client on the view that renders the data.

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def your_view(request):
    ...
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.