user140888
user140888

Reputation: 609

Send a cookie in http requests from frontend to backend with Angular

I am developing a web-application using AngularJS.

The application is realized with:

In my frontend, in the main controller, I create a cookie using $cookieStore, in this way:

// Setting sessionID in the cookie
$cookieStore.put('sessionID', $scope.contextData.sessionId);

Now, I want to send the information of this cookie to the generic backend service that I call. For example, one of my call has this form:

$http({
       method: "GET",
       url: urlBase + "/context/person"
    }).success(function(result, status, headers, config) {
        $scope.currentPerson = result;
    });

How can I send the cookie? Thanks in advance.

Upvotes: 1

Views: 9643

Answers (2)

Ankit Sharma
Ankit Sharma

Reputation: 38

$http({
   method: "POST",
   url: urlBase + "/context/person"
}).success(function(result, status, headers, config) {
    $scope.currentPerson = result;
});

or you can use the angular shortcut post method :

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

POST method will send the cookies to the backend. In backend you can use JSON.parse(req.cookies) to get your cookies.

Upvotes: 0

Manuel Spigolon
Manuel Spigolon

Reputation: 12870

You should set the argument withCredentials see docs

By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted, but the browser will reject any response that does not have the Access-Control-Allow-Credentials: true header, and not make the response available to the invoking web content.

I assume you are running the script in the same domain of the server because

Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain. The header will not be set for cross-domain requests.

Upvotes: 3

Related Questions