【问题标题】:React Django CSRF token missing or incorrectReact Django CSRF 令牌丢失或不正确
【发布时间】:2022-01-25 19:08:29
【问题描述】:

在动作文件中的代码:

...
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 令牌丢失或不正确,如何解决这个问题,谢谢。 应用程序重新启动,没有任何更改。此外,请求已更改为 localhost:3000 而不是 8000。

【问题讨论】:

  • 您从哪里发送请求?JavaScript 前端应用程序?
  • 从反应应用发送

标签: reactjs django


【解决方案1】:

Django 可以通过装饰器在 cookie 中提供 CSRF 令牌。然后你可以从你的 cookie 中获取它并将其添加为 HTTP 标头:

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)

【讨论】:

  • 能否请您澄清一下主视图是什么意思,有注册视图登录视图等...
  • 用户与之交互的第一个视图。用于向您的用户“提供”反应代码的一种。这样就可以确定cookie已经设置好了。
猜你喜欢
  • 2021-07-14
  • 2021-11-13
  • 2012-04-20
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2016-06-10
  • 2017-09-14
相关资源
最近更新 更多