ajaxのPOST送信で403が返却される場合の対処方法
5370 ワード
- ログイン後、ajaxでPOST送信した時に403が返却される場合、CSRFをリクエストヘッダーに設定すればPOST送信が出来るようになる
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function() {
let token = $("meta[name='_csrf']").attr("content");
let header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).off('click', '#hoge').on('click', '#hoge', function() {
$.ajax({
type : "post",
//type : "get",
url : "api/hoge",
contentType : "application/json"
})
.done( (result) => {
alert(result.msg);
})
})
});
</script>
</head>
<body>
<input type="button" id="hoge" value="ボタン" />
</body>
<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
</html>
Author And Source
この問題について(ajaxのPOST送信で403が返却される場合の対処方法), 我々は、より多くの情報をここで見つけました https://qiita.com/teradatk/items/e112dc39188a380d24d9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .