54

I've been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server. I did this by setting these headers:

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");

I'm able to send AJAX requests from AngularJS to the backend but I'm facing a problem when I try to get an attribute of a session. I believe this is because the sessionid cookie doesn't get send to the backend.

I was able to fix this in jQuery by setting withCredentials to 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);
        }
    })
});

The problem that I'm facing is that I can't get this to work in AngularJS with the $http service. I tried it like this:

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

Can anyone tell me what I'm doing wrong?

3 Answers 3

76

You should pass a configuration object, like so

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

or in older versions:

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

See also your other question.

Sign up to request clarification or add additional context in comments.

7 Comments

+1 and if you are using ngresource you would declare the method call with something like 'getUserDetail': { method:'GET', params: {}, withCredentials: true}
In this case only withCredentials: true goes in that form or also options Content-Type, Accept, crossDomain, Access-Control-Allow-Credentials/Origin/Headers?
In this case older and newer version is?
@wanttobeprofessional I didn't check, feel free to suggest an edit if you find the exact boundaries. This stuff was old in 2014…
Does anyone know, why this make such a huge difference? I compared all requests and responses (OPTIONS and POST) with and without withCredentials and could not find any difference. Maybe chrome's debug mode is hiding some details?
|
59

In your app config function add this :

$httpProvider.defaults.withCredentials = true;

It will append this header for all your requests.

Dont forget to inject $httpProvider

EDIT : 2015-07-29

Here is another solution :

HttpIntercepter can be used for adding common headers as well as common parameters.

Add this in your config :

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

and create factory with name 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;
}

Comments

0

Clarification:

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

should be

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

as per https://docs.angularjs.org/api/ng/service/$http

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.