5

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.

4
  • Did you try npmjs.com/package/django-react-csrftoken? Commented May 6, 2018 at 15:00
  • to Arpit, Yeah, that's the one also I've tried. I setted it for my view that does some register things Commented May 6, 2018 at 15:10
  • 1
    Possible duplicate of CSRF with Django, React+Redux using Axios Commented May 6, 2018 at 15:43
  • To Kiara, yeah I've also tried it. Commented May 6, 2018 at 15:55

1 Answer 1

2

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})

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.