尝试在Spring MVC和Thymeleaf中使用React / Ajax调用

编程入门 行业动态 更新时间:2024-10-23 05:46:52
本文介绍了尝试在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="www.w3/1999/xhtml" xmlns:th="www.thymeleaf"> <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调用

本文发布于:2023-11-24 21:11:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626846.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:MVC   Spring   Thymeleaf   Ajax   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!