purolor
purolor

Reputation: 53

ReactJS & Django : How can I send csrf token with axios in a proper way?

I'm pretty new to using ReactJS with Django.

What I want is simple. I want to send a request to make an account. Front-End server and the Back-End server are completely divided. They only communicates with AJAX, and nothing more, they're not even in the same server.

I tried several ways to send a request to make an account, and nothing worked.

Here's what I tried in JavaScript:

  1. Add an option called withCredentials:true on axios. This adds cookie on header, but django says "csrftoken incorrect or not set."

  2. Set the following:

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

-> this doesn't make any effects.

  1. Set the following:

    axios.defaults.headers.common = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-TOKEN' : (document.cookie).replace("csrftoken=", "")
    };
    

-> this makes axios to make only "option" method requests. but I don't know why and of course, this doesn't work.

Here's what I changed in Django's settings.py:

CSRF_COOKIE_NAME = "X-CSRFToken"
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_EXPOSE_HEADERS = (
    'Access-Control-Allow-Origin: *',
)

and of course, I added @ensure_csrf_cookie just above the view that does some register things.

Is there any way to fix this? I spend a lot of my time for this. I REALLY need your help. thanks.

Upvotes: 5

Views: 2821

Answers (1)

Mikebarson
Mikebarson

Reputation: 622

You can install js-cookie via npm (or other methods that suites you) link here

Call the Cookies in js-cookie like so: import Cookies from 'js-cookie';

Then take the cookies by doing: Cookies.get()

Cookies.get() gives you an object which contains the csrftoken. So you can do something like this overall:

const cookies = Cookies.get()

Then in your headers in your axios request you can add this:

headers: new Headers({"Content-Type": "application/json", 'X-CSRFToken': cookies.csrftoken})

Upvotes: 3

Related Questions