gpt4 book ai didi

javascript - 尝试将 React/Ajax 调用与 Spring MVC 和 Thymeleaf 结合使用

转载 作者:行者123 更新时间:2023-11-29 16:08:40 25 4
gpt4 key购买 nike

根据文档,我应该能够在 header 中包含 CSRF token ,使用 jquery 获取它们,并将它们包含在我的 ajax 调用的 header 中。

不幸的是,包括

<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}">

而不是实际的 token ,所以没有什么可抓取的。

有没有人用这种方式成功处理 ajax post/puts/deletes?

引用: http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html

最佳答案

你忘记了前缀“th”。您的模板应如下所示:

<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);
}
});

关于javascript - 尝试将 React/Ajax 调用与 Spring MVC 和 Thymeleaf 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34325312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com