LoginSignup
6
6

More than 3 years have passed since last update.

ajaxのPOST送信で403が返却される場合の対処方法

Posted at
  • ログイン後、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>

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6