1

I am developing a web-application using AngularJS.

The application is realized with:

  • a frontend, a component without logic, that simply queries a backend many times, in order to receive from it all the needed data;
  • a backend, containing many RESTful services, and each of them returns data to the frontend (if the frontend calls it).

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.

4

2 回答 2

3

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.

于 2015-03-10T11:33:38.910 回答
0
$http({
   method: "POST",
   url: urlBase + "/context/person"
}).success(function(result, status, headers, config) {
    $scope.currentPerson = result;
});

或者您可以使用角度快捷方式发布方法:

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

POST方法会将 cookie 发送到后端。在后端,您可以使用JSON.parse(req.cookies)来获取您的 cookie。

于 2016-07-26T11:22:56.287 回答