Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/csrf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ token in the form.
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
</form>

Be careful to write the ``name`` attribute of the input tag as it is, with an underscore.
If CSRF protection is enabled and the name does not match with the value of ``WTF_CSRF_FIELD_NAME`` (whose default value is ``'csrf_token'``), you get the Bad Request: CSRF token missing error.
If you want to use something else as the name attribute (although not recommended), ensure to set the ``WTF_CSRF_FIELD_NAME`` to ``'anyStringYouWant'`` in your app config.

JavaScript Requests
-------------------

Expand Down Expand Up @@ -82,6 +86,34 @@ In Axios you can set the header for all requests with ``axios.defaults.headers.c
axios.defaults.headers.common["X-CSRFToken"] = "{{ csrf_token() }}";
</script>

To send the form data of other form inputs to your backend route using Vanilla Js for example.

.. sourcecode:: html+jinja

<script type="text/javascript">
const formElement = document.getElementById("form-id");

formElement.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(formElement);

const response = fetch('/flask-route', {
method: 'POST',
headers: {
//Other header settings
'X-CSRF-TOKEN': {{ csrf_token() }}
},
body: JSON.stringify({
"csrf_token": {{ csrf_token() }},
"<input-name>": formData.get("<input-name>"),
})
});

const data = response.json();
//Do stuff with response data
})
</script>

Customize the error response
----------------------------

Expand Down