Ad

React Calling Django API CSRF

- 1 answer

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

Ad

Answer

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):
    ...
Ad
source: stackoverflow.com
Ad