猿问

在 Fetch JS for Django 中添加 CSRF

我的 django 模板中有以下 JS 代码:


fetch("http://127.0.0.1:8000/api/endpoint", {

      method: "POST",

      body: $("#form").serializeArray(),

    }).then(function(data) {

    });

在 api/endpoint 中,我得到:


Forbidden (CSRF token missing or incorrect.): /api/endpoint

如何在 fetch 中添加 csrf 令牌?


阿晨1998
浏览 141回答 3
3回答

慕无忌1623718

我在一个类似的项目中遇到了几个小时的问题。我终于找到了解决方案!我希望这个信息帮助。我正在使用的脚本不在 django 模板上,所以使用csrfmiddlewaretoken: '{{ csrf_token }}'对我不起作用。我在"credentials": 'same-origin'上面列出的,而且还包括"X-CSRFToken": getCookie("csrftoken")了,它使用了底部包含的功能。这是我需要的第二点。所以你的代码应该是这样的:fetch("http://127.0.0.1:8000/api/endpoint", {&nbsp; method: "POST",&nbsp; body: $("#form").serializeArray(),&nbsp; credentials: 'same-origin',&nbsp; headers: {&nbsp; &nbsp; &nbsp; "X-CSRFToken": getCookie("csrftoken")&nbsp; }}).then(function(data) {}).catch(err => console.log(err));然后你需要添加这个函数:function getCookie(name) {var cookieValue = null;if (document.cookie && document.cookie !== '') {&nbsp; &nbsp; var cookies = document.cookie.split(';');&nbsp; &nbsp; for (var i = 0; i < cookies.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var cookie = jQuery.trim(cookies[i]);&nbsp; &nbsp; &nbsp; &nbsp; // Does this cookie string begin with the name we want?&nbsp; &nbsp; &nbsp; &nbsp; if (cookie.substring(0, name.length + 1) === (name + '=')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cookieValue = decodeURIComponent(cookie.substring(name.length + 1));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}return cookieValue;}当然,该方法必须在同一页面上。取自 Django 文档。 https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax我从这篇文章中找到了这些信息: 来自用户Ska的https://stackoverflow.com/a/43943556

紫衣仙女

在你的身体内部,你可以像这样在你的 ajax 请求中传递 csrf 令牌:body : {&nbsp; &nbsp;// Other stuff&nbsp; &nbsp;csrfmiddlewaretoken: '{{ csrf_token }}'}这应该可以解决您的问题。编辑:默认情况下,Fetch 在其请求中不包含 Cookie。为此,您需要在您的 fetch 请求中添加这一行作为 on 选项:credentials : 'include' // For Corscredentials : 'same-origin' // For same origin requests&nbsp;

慕姐8265434

就我而言,我使用的是纯 Javascript 和 Django。我必须在我的 HTML 布局中隐藏一个 {% csrf_token %} 以便我可以在我的 fetch 请求中访问它,如下所示:HTML 模板:<head>&nbsp;&nbsp; <title>Page title</title>&nbsp; {% csrf_token %}</head>index.js:csrf_token = document.getElementsByName('csrfmiddlewaretoken')[0].valuefetch(`${url}`, {&nbsp; &nbsp; &nbsp; &nbsp; method : 'put',&nbsp; &nbsp; &nbsp; &nbsp; body : JSON.stringify(your_dat),&nbsp; &nbsp; &nbsp; &nbsp; headers: { "X-CSRFToken": csrftoken },&nbsp; &nbsp; &nbsp; &nbsp; credentials : 'same-origin',&nbsp; &nbsp; })它可能不是最漂亮的代码
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答