使用fetch post请求进行正确的Django CSRF验证

Cor*_*ory 3 javascript django django-csrf fetch-api

我正在尝试使用JavaScript的fetch库来向我的Django应用程序提交表单.但无论我做什么,它仍然抱怨CSRF验证.

关于Ajax的文档提到了指定我尝试过的头文件.

我还尝试从templatetag中获取令牌并将其添加到表单数据中.

这两种方法似乎都不起作用.

以下是包含表单值和标题的基本代码:

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,
})
Run Code Online (Sandbox Code Playgroud)

我能够使用JQuery,但想尝试使用fetch.

Cor*_*ory 12

想出这个.问题是fetch 默认情况下不包含cookie.

简单的解决方案是添加credentials: "same-origin"到请求并且它可以工作(使用表单字段但没有标题).这是工作代码:

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',
})
Run Code Online (Sandbox Code Playgroud)


ano*_*ous 12

你的问题非常接近成功。如果您不想要 form 方法,这是一种json方式。顺便说一句,@Cory 的表单方法非常简洁。

  1. 第三个图书馆的整洁方式
let data = {
    'file': file,
    'fileName': file.name,
};
// You have to download 3rd Cookies library
// https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
let csrftoken = Cookies.get('csrftoken');
let response = fetch("/upload/", {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { "X-CSRFToken": csrftoken },
})
Run Code Online (Sandbox Code Playgroud)

2.另一种繁琐的方式,但没有任何第三个库

let data = {
    'file': file,
    'fileName': file.name,
};
let csrftoken = getCookie('csrftoken');
let response = fetch("/upload/", {
    method: 'POST',
    body: JSON.stringify(data),
    headers: { "X-CSRFToken": csrftoken },
})

// The following function are copying from 
// https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
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;
}
Run Code Online (Sandbox Code Playgroud)


Abh*_*rt- 5

有一个简单的解决方案,无需任何第三方库。在您的模板脚本中。做这个。

fetch("your_post_url",
        {
            method: "POST",
            body: JSON.stringify(data),
            headers: { "X-CSRFToken": '{{csrf_token}}' },
        }
    ).then(res => {
        //process your response
    }
Run Code Online (Sandbox Code Playgroud)