【问题标题】:How send POST request in angularjs with _csrf?如何使用 _csrf 在 angularjs 中发送 POST 请求?
【发布时间】:2016-01-06 09:23:52
【问题描述】:

我想在 Spring Security 下发送 POST 请求到服务。 如果我使用表单提交(带有隐藏输入) - 它工作正常。 但我不知道,如何使用 $http.post 发送请求。 我的表格:

<form method="POST" type="submit" action="http://localhost:8888/rest/post1" />
    <button>345</button>
    <input name="${_csrf.parameterName}"
           value="${_csrf.token}" />
</form>

它工作。

我保存参数:

<script>
        var a = "${_csrf.parameterName}";
        var b = "${_csrf.token}";
</script>

我的 ng-click 功能:

$http.post('http://localhost:8888/rest/post1', {"_csrf": b}, {
    "headers" :
    { "_csrf" : b }
}).success(function(data) {
    console.log("ok");

}).error(function(){

    console.log("no");
});

它总是写“不”。

我认为,需要将变量作为 webForm 发送,但是如何在 $http.post 中发送?

提琴手写:Content-Type is 'application/json'; this inspector supports 'x-www-form-urlencoded' only

服务器控制台:

org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
WARNING: Request method 'POST' not supported

请帮帮我!

【问题讨论】:

标签: angularjs jsp spring-security csrf


【解决方案1】:

您可能需要在请求标头中设置“_csrf”。您将它作为方法的参数传递。这行不通。我不太了解 angular.js,但您必须将其作为请求标头或请求有效负载传递。我找到了一些参考。就是这样:

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

希望这可以帮助您解决问题。干杯!!!

【讨论】:

    【解决方案2】:

    我解决了这个)

    var request = $http({
        method: "post",
        url: "http://localhost:8888/rest/post1",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(){return a+"="+b;},
        data: {}
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2011-07-15
      • 2019-07-08
      相关资源
      最近更新 更多