繁体   English   中英

反应 Django CSRF 令牌丢失或不正确

[英]React Django CSRF token missing or incorrect

在动作文件中的代码:

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

它正在工作; 然后localhost:8000移动到package.json作为代理,之后出现CSRF token missing or wrong 的问题,如何解决,谢谢。 应用程序重新启动,没有任何更改。 此外,请求已更改为localhost:3000而不是 8000。

Django 可以通过装饰器在您的 cookies 中提供 CSRF 令牌。 然后你可以从你的 cookies 中得到它,并将其添加为 HTTP header:

视图.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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