AngularJS - Does $resource requests send cookies automatically?

6k Views Asked by At

I am using a $resource in my angularJS app. Does it send automatically my cookies? I am doing requests on the same domain.

3

There are 3 best solutions below

1
On

Browser will always send a cookie along with the request (no matter if it's an XHR request or not) as long as all assumptions are met (same domain, matching path, matching port, same protocol, not expired, etc.).

Since $resource service is just a simple Ajax wrapper your cookies will/should be sent (if everything's in place).

2
On

No. But if you want to send cookies, then you can try $cookies service to get the cookie and send with API either in the payload or included in the header.

You can also set the cookie in a default header (with $cookies service injected) so you don't have to specify it in all API calls.

var cookie = $cookies.myCookie; // suppose you already set $cookies.myCookie= 'xxx';
$http.defaults.headers.post.Cookies = cookie;
0
On

Note that running different applications on the same domain but on different ports might also be a reason for why cookies are not sent.

Cookies should not be port specific (regarding SOP), but CORS definitely is. Also see Are HTTP cookies port specific?

In my experience no current Browser (FF 47, Chrome 51, IE11) sends cookies for example from localhost:3000 to localhost:8080 in a XHR request.