22

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.

Jens
  • 20,533
  • 11
  • 60
  • 86
Cory
  • 22,772
  • 19
  • 94
  • 91

3 Answers3

27

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',
})
Community
  • 1
  • 1
Cory
  • 22,772
  • 19
  • 94
  • 91
  • 1
    Thank you, this is the simplest solution I've seen so far and it works like a charm. – Lewy Blue Jul 29 '19 at 07:39
  • @Dr.DOOM I would think so, you'd just need to use the flask-specific way of accessing the token and passing it to the view. – Cory Oct 15 '19 at 04:34
24

Your question is very close to success. Here is a json way if you do not want the form method. Btw, @Cory's form method is very neat.

  1. Neat way with 3rd library
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 },
})

2. Another cumbersome way, but without any 3rd library

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;
}
anonymous
  • 1,372
  • 1
  • 17
  • 22
  • somehow the accepted answer by Cory did not work for me. neither did the super simple one by Abhinas of just typing {{csrf_token}} but here the second one worked like a charm. I also don't see it as particularly cumbersome, copy & pasting one javascript function is a small price to pay and I definitely prefer it to adding a library. – Werner Trelawney Jul 23 '23 at 10:40
4

There is a simple solution to this without any third party libraries. In your templates scripts. Do this.

fetch("your_post_url",
        {
            method: "POST",
            body: JSON.stringify(data),
            headers: { "X-CSRFToken": '{{csrf_token}}' },
        }
    ).then(res => {
        //process your response
    }
  • i tried this, but i still get the error, the output in the Python terminal is `Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /tweet` – waffledood Jan 08 '23 at 05:47