Bikash Pandey
Bikash Pandey

Reputation: 35

Flask AJAX: Bad Request. The CSRF token is missing

I am facing a problem while sending a request using ajax to flask server. I have attached HTML, js and python file for reference. Html Form Image

AJAX request code

python file

I have tried various solutions for this problem researching on the internet. I will be grateful if I got out of this problem.

Upvotes: 1

Views: 3012

Answers (2)

Rinaldi Pratama
Rinaldi Pratama

Reputation: 47

Or you can use the ajaxSetup() method from jQuery. This method will set default values for future AJAX requests. It should look like this:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajaxSetup({
            headers: {
                "X-CSRFToken": "{{ csrf_token() }}"
            }
        });

        // Your javascript codes...
    });
</script>

Upvotes: 0

Kenny Aires
Kenny Aires

Reputation: 1438

On your Ajax call, you must add your CSRF Token on request header, not on payload data as you are sending now, e.g:

var csrf_token = "{{ csrf_token() }}";

$.ajax({
    type: 'POST',
    url: '/login',
    headers: {
        "X-CSRFToken": csrf_token,
    }
    data: {
     ...

Hope it suits you well :)

Upvotes: 3

Related Questions