使用获取帖子请求进行正确的Django CSRF验证 [英] Proper Django CSRF validation using fetch post request
问题描述
我正在尝试使用JavaScript的获取库表单提交到我的Django应用程序。但是,无论我做什么,它仍然抱怨CSRF验证。
I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation.
Ajax上的文档提到指定我尝试过的标头。
The docs on Ajax mentions specifying a header which I have tried.
我还尝试获取令牌从模板标签中添加并将其添加到表单数据中。
I've also tried grabbing the token from the templatetag and adding it to the form data.
这两种方法似乎都不起作用。
Neither approach seems to work.
这是包含表单值和标头的基本代码:
Here is the basic code that includes both the form value and the header:
let data = new FormData();
data.append('file', file);;
data.append('fileName', file.name);
// add form input from hidden input elsewhere on the page
data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value'));
let headers = new Headers();
// add header from cookie
const csrftoken = Cookies.get('csrftoken');
headers.append('X-CSRFToken', csrftoken);
fetch("/upload/", {
method: 'POST',
body: data,
headers: headers,
})
我能够使用JQuery,但想尝试使用 fetch
。
I'm able to get this working with JQuery, but wanted to try using fetch
.
推荐答案
弄清楚了这一点。问题是获取
不包含Cookie的原因默认。
Figured this out. The issue is that fetch
doesn't include cookies by default.
简单的解决方案是在请求中添加凭据: same-origin
并它可以工作(使用表单字段,但没有标题)。这是工作代码:
Simple solution is to add credentials: "same-origin"
to the request and it works (with the form field but without the headers). Here's the working code:
let data = new FormData();
data.append('file', file);;
data.append('fileName', file.name);
// add form input from hidden input elsewhere on the page
data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value'));
fetch("/upload/", {
method: 'POST',
body: data,
credentials: 'same-origin',
})
这篇关于使用获取帖子请求进行正确的Django CSRF验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!