51

我一直在研究一个 AngularJS 项目,该项目必须将 AJAX 调用发送到一个 restfull 网络服务。这个网络服务在另一个域上,所以我必须在服务器上启用 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");

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

通过将 withCredentials 设置为 true,我能够在 jQuery 中解决此问题。

$("#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);
            });

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

4

3 回答 3

74

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

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

或在旧版本中:

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

另请参阅您的其他问题

于 2013-01-02T19:24:12.093 回答
55

在您的应用程序配置函数中添加:

$httpProvider.defaults.withCredentials = true;

它将为您的所有请求附加此标头。

别忘了注入$httpProvider

编辑:2015-07-29

这是另一个解决方案:

HttpIntercepter 可用于添加公共标头以及公共参数。

在你的配置中添加这个:

$httpProvider.interceptors.push('UtimfHttpIntercepter');

并创建具有名称的工厂UtimfHttpIntercepter

    angular.module('utimf.services', [])
    .factory('UtimfHttpIntercepter', UtimfHttpIntercepter)

    UtimfHttpIntercepter.$inject = ['$q'];
    function UtimfHttpIntercepter($q) {
    var authFactory = {};

    var _request = function (config) {
        config.headers = config.headers || {}; // change/add hearders
        config.data = config.data || {}; // change/add post data
        config.params = config.params || {}; //change/add querystring params            

        return config || $q.when(config);
    }

    var _requestError = function (rejection) {
        // handle if there is a request error
        return $q.reject(rejection);
    }

    var _response = function(response){
        // handle your response
        return response || $q.when(response);
    }

    var _responseError = function (rejection) {
        // handle if there is a request error
        return $q.reject(rejection);
    }

    authFactory.request = _request;
    authFactory.requestError = _requestError;
    authFactory.response = _response;
    authFactory.responseError = _responseError;
    return authFactory;
}
于 2015-04-13T10:34:17.770 回答
0

澄清:

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

应该

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

根据https://docs.angularjs.org/api/ng/service/$http

于 2019-04-26T00:37:42.270 回答