尝试在Spring MVC和Thymeleaf中使用React / Ajax调用 [英] Trying to use React/Ajax calls with Spring MVC and Thymeleaf
本文介绍了尝试在Spring MVC和Thymeleaf中使用React / Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据文档,我应该能够在标题中包含CSRF令牌,使用jquery捕获它们,并将它们包含在我的Ajax调用的标题中。
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.
不幸的是,包括
<html class='default' xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset='UTF-8'/>
<meta http-equiv='X-UA-Compatible' content='IE=Edge,chrome=1' />
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
...
</html>
输出:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="_csrf" content="${_csrf.token}">
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}">
不是实际的令牌,因此没有东西可抢。
And not the actual token so there is nothing to grab.
有人用这种方式处理ajax发布/提交/删除吗?
Has anyone had success with this way of handling ajax post/puts/deletes?
参考:
http:/ /docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html
推荐答案
您忘记了前缀 th。您的模板应如下所示:
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}"/>
和您的ajax调用:
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);
}
});
这篇关于尝试在Spring MVC和Thymeleaf中使用React / Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文