小编典典

AngularJS withCredentials

angularjs

我一直在研究AngularJS项目,该项目必须将AJAX调用发送到restfull
Web服务。此Web服务在另一个域上,因此我必须在服务器上启用cors。我通过设置这些标题来做到这一点:

cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

我可以将AngularJS的AJAX请求发送到后端,但是当我尝试获取会话的属性时遇到了问题。我相信这是因为sessionid cookie不会发送到后端。

我可以通过将withCredentials设置为true来解决此问题。

$("#login").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/login",
        data : '{"identifier" : "admin", "password" : "admin"}',
        contentType : 'application/json',
        type : 'POST',
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log(data);
        }
    })
});

$("#check").click(function() {
    $.ajax({
        url: "http://localhost:8080/api/ping",
        method: "GET",
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            console.log(data);
        }
    })
});

我面临的问题是我无法通过$ http服务在AngularJS中使用它。我这样尝试过:

$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}).
            success(function(data) {
                $location.path('/');
                console.log(data);
            }).
            error(function(data, error) {
                console.log(error);
            });

谁能告诉我我在做什么错?


阅读 405

收藏
2020-07-04

共1个答案

小编典典

您应该像这样传递一个配置对象

$http.post(url, {withCredentials: true, ...})

或旧版本中:

$http({withCredentials: true, ...}).post(...)
2020-07-04