How to use Flask-WTForms CSRF protection with AJAX?

前端 未结 1 1694
天涯浪人
天涯浪人 2021-02-05 11:50

Flask-WTForms provides CSRF protection. It works great when using normal HTML forms, but the process is less clear when using AJAX. I have a file upload in my form, and I spli

1条回答
  •  无人及你
    2021-02-05 12:12

    The documentation speaks a bit about implementing CSRF protection with regards to AJAX.

    You can enable the module:

    from flask_wtf.csrf import CsrfProtect
    
    CsrfProtect(app)
    

    and then use this in your AJAX POST call:

    
    
    var csrftoken = $('meta[name=csrf-token]').attr('content')
    
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken)
            }
        }
    })
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题