Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http set cookie on each request after login

I'm having troubles with $http calls in AngularJS. I've created the following services

    crApp.service('authService', function ($http) {

    var urlBase = 'http://192.168.xx.xx:8081';

    // POST api/login/
    this.login = function (credentials) {
    return $http.post(urlBase + "/api/login", credentials);
    };

  // POST api/logout/
  this.logout = function () {
    return $http.post(urlBase + "/api/logout/", "");
  };

}); //end service

crApp.service('dataService', function ($http) {

  var urlBase = 'http://192.168.xx.xx:8081';

  // POST api/query/
  this.pull = function (query) {
    return $http.post(urlBase + "/api/query", query);
  };

From the controller I call the login method:

$scope.login = function(){
    authService.login(credentials)
        .success(function(data) {
            console.log("RESULT LOGIN: " + data );
        })
        .error(function(data, status, headers, config) {
            console.log(data);
            console.log(status);
            console.log(headers);
            console.log(config);
        });
};

So far so good and I receive a response where a cookie is set: enter image description here

After succesfull login I call the following method:

var locations = { query: "from location select uid, name, description, address, phone", dataFormat: "verbose" };
$scope.getLocations = function() {
    dataService.pull(portals)
        .success(function (data) {
            console.log("RESULT QUERY: " + data)
        })
        .error(function(data, status, headers, config) {
            console.log("Query niet gelukt!");
            console.log(data);
            console.log(status);
            console.log(headers);
            console.log(config);
        });
};

Result:

enter image description here

So cookie is not set in the headers. I'm using AngularJS 1.3.15 and calls are made to a remote server on a different domain, but it does work in the REST Client tool in WebStorm (Jetbrains). So it must be something i'm missing in Angular!??

Hopefully someone can help me out.

like image 803
marlonlaan Avatar asked May 27 '15 20:05

marlonlaan


1 Answers

You need to set withCredentials = true in the $http config to allow cookies to be set on CORS requests. This article explains more about cookies and CORS.

In your app config:

$httpProvider.defaults.withCredentials = true;

For example:

angular.module('myApp', [])
.config(['$httpProvider'){
    $httpProvider.defaults.withCredentials = true;
}]);

You can read about this option in the $http provider documentation.

like image 146
Scott Avatar answered Sep 19 '22 02:09

Scott