pythonajaxflaskcsrf-token

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.


Solution

  • 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 :)