簡體   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