Trying To Use React/ajax Calls With Spring Mvc And Thymeleaf
according to the docs, I should be able to include the CSRF tokens in the header, grab them with jquery, and include them in the headers of my ajax calls. Unfortunately, including
Solution 1:
You forget the prefix "th". your template should look like this:
<meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>
and your ajax call:
var token = $('#_csrf').attr('content');
var header = $('#_csrf_header').attr('content');
$.ajax({
type: "POST",
url: url,
beforeSend: function (xhr) {
xhr.setRequestHeader(header, token);
},
success: function (data, textStatus, jqXHR) {
alert(status);
},
error: function (request, status, error) {
alert(status);
}
});
Solution 2:
Here is how I did my ajax csrf.
$(function() {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader(header, token);
}
}
I also use ajaxForm plugin to submit forms, in which case i embed the csrf into the action url.
Hope that works for you.
Post a Comment for "Trying To Use React/ajax Calls With Spring Mvc And Thymeleaf"