简体   繁体   中英

React Django CSRF token missing or incorrect

In action file the code:

...
const config = {
      headers:{
        'Content-type': 'application/json'
      }
    }
    const {data} = await axios.post('http://localhost:8000/api/register/',
                {'email':email, 'password':password}, config)
...

It's working; then localhost:8000 moved to package.json as a proxy, after that got an issue CSRF token missing or incorrect , how to fix that, thanks. Application was restarted with no changes. Furthermore, the request has changed to localhost:3000 instead of 8000.

Django can provide the CSRF token in your cookies with a decorator. Then you can get it from your cookies and add it as a HTTP header:

views.py:
from django.views.decorators.csrf import ensure_csrf_cookie


# add this decorator to your main view 
# (the one which serves your first html/javascript code, not the /api/register one)
@ensure_csrf_cookie 
def index(request):
    ...
javascript:
    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 = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
...

const config = {
      headers:{
        'Content-type': 'application/json',
        'X-CSRFToken': getCookie("csrftoken") // added the csrf cookie header
      }
    }
    const {data} = await axios.post('http://localhost:8000/api/register/',
                {'email':email, 'password':password}, config)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM