Ajax POST results in a 405 (Method Not Allowed) - Spring MVC

前端 未结 3 384
离开以前
离开以前 2020-12-18 06:16

I\'m trying to make an ajax call to my Spring controller/action with POST method, and return an object from the server with @ResponseBody. The strange situation is that it s

相关标签:
3条回答
  • 2020-12-18 06:28

    $.ajaxSetup({
        dataType: "json",
        beforeSend: function(xhr, settings){
            var csrftoken = $.cookie('CSRF-TOKEN');
            xhr.setRequestHeader("X-CSRF-TOKEN", csrftoken);
        },
    });

    0 讨论(0)
  • 2020-12-18 06:29

    In my case, with same problem, helps this:

    • add taglib:
     <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
    
    • add in jsp body:
    <sec:csrfMetaTags />
    
    • add in ajax
    headers: {"X-CSRF-TOKEN": $("meta[name='_csrf']").attr("content")}
    

    P.S. Thanks to Illya Shulgin, cool ansver, now it here.

    0 讨论(0)
  • 2020-12-18 06:42

    After many hours of research and tests, I finally got it, ant it was a (very very) stupid situation. So, in my question I said

    so I disabled it (csrf on spring-security.xml) and still have the issue.

    No, I didn't disabled it. I was trying to disable it doing

    <!--
    <csrf/>
    -->
    

    But I should be doing:

    <csrf disabled="true"/>
    

    Commenting csrf tag does NOT disable csrf, this is because csrf is enabled by default! After find the problem is really easy to say that is a stupid mistake, but as I added csrf tag to enable it, I thought that commenting it would disable it. Find the answer on Spring Documentation

    Now, back into my problem. To fix the 405 error message in a POST AJAX call WITH CSRF ENABLED, it was really easy. I keep the csrf parameters in JS variables like this:

    <script type="text/javascript">
        var csrfParameter = '${_csrf.parameterName}';
        var csrfToken = '${_csrf.token}';
    </script>
    

    and then my ajax call looks like this:

    var jsonParams = {};
    jsonParams['parentId'] = 1;
    jsonParams[csrfParameter] = csrfToken;
    $.ajax({
        type: 'POST',
        cache: false,
        url: /admin/events/loadEvents,
        data: jsonParams,
        dataType = 'json',
        contentType = 'application/json',
    
        ...
    });
    

    Working like a charme. Hope that helps someone in the future.

    0 讨论(0)
提交回复
热议问题