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.
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,
})
I'm able to get this working with JQuery, but wanted to try using fetch
.
Figured this out. The issue is that fetch
doesn't include cookies by default.
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',
})