0

This question has been asked before, but those solutions didn't work for me that well:

Fetch, set-cookies and csrf

Proper Django CSRF validation using fetch post request

Right now the content of my post request is correct and being, but the 403 error still shows up.

        const url = "/post/create"
        let csrftoken = Cookies.get('csrftoken'); //using library


        const headers = new Headers({
                'X-CSRF-TOKEN': csrftoken
            });
            return fetch(url, {
                method: 'POST',
                headers,
                credentials: 'same-origin',
                mode: 'same-origin',
                body: JSON.stringify({
                    content: content
                })
            });

Do you have any ideas?

EDIT: This is the solution I found

        fetch(url, {
            method: 'POST',
            mode: "same-origin",
            headers: {
                "X-CSRFToken": csrftoken,
                "Accept": "network/json",
                "Content-Type": "network/json",
            },
            body: JSON.stringify({
                content: content
            })
wurstm162
  • 71
  • 1
  • 6

1 Answers1

0

It should be X-CSRFToken not X-CSRF-TOKEN. See more here.

datosula
  • 1,496
  • 5
  • 10
  • It's really weird but when I use X-CSRFToken the POST request isn't even submited. It only works with the latter on for me:( – wurstm162 Feb 22 '21 at 10:23
  • If you're using jquery you may send it as a part of post data, like `var postData = $('your-form').serializeArray(); postData['csrfmiddlewaretoken'] = Cookies.get('csrftoken');` and send `$.post(url, postData,...);` – datosula Feb 22 '21 at 10:31