」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Django CSRF驗證為何在Ajax POST請求中失敗?

Django CSRF驗證為何在Ajax POST請求中失敗?

發佈於2025-04-16
瀏覽:179

Why is My Django CSRF Check Failing with an Ajax POST Request?

Django CSRF Check Failing with Ajax Post Request

As outlined in Django's documentation, enabling CSRF protection helps prevent malicious cross-site request attacks. By following the instructions, you attempted to implement the CSRF check with Ajax posting but are still encountering rejection.

To troubleshoot this issue, consider the following steps:

  1. Verify Token Existence:
    Ensure that the JavaScript code is fetching the CSRF token and將其存儲在稱為CSRFTOKON的變量中。在設置標頭之前,應該存在此令牌:

    $。 var csrftoken = getCookie('csrftoken'); xhr.setRequestheader(“ x-csrftoken”,csrftoken);
    $.post("/memorize/", data, function (result) { ... });
    
    var csrftoken = getCookie('csrftoken');
    xhr.setRequestHeader("X-CSRFToken", csrftoken);
    之後,在獲取標記,明確的請求中使用ajax neckEnterequestheader的標題,正文:
  2. 從django檢查響應主體,以查看是否明確地提到了缺失或無效的CSRF令牌。
  3. bose a header ass ax emp to aje inj inj inj ins inj如下:啟用調試:通過添加debug = true the the設置。這可能會在響應主體中提供其他錯誤消息或提示。
    完成這些步驟後,請重新提交AJAX請求,以查看CSRF檢查是否成功。
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3