0

I have an angular app running at localhost:4200 My API backend runs at localhost:8080

The API backend provides auth endpoint which sets a cookie:

localhost:4200 -> localhost:8080 POST /auth?creds=mycreds responds 204 Set-Cookie: mycookie=myvalue; HttpOnly

The following XHR requests from localhost:4200 to localhost:8080 are not transmitting the cookie to the backend. I don't get why.

R. G
  • 257
  • 2
  • 14

1 Answers1

0

Cookie never transmit on cross domain due to security issue. Cookie storage always attached to request if domain of request is same. But you can get your cookie from browser and add it your response manually. Use following code:

postData(dataToBePosted) {
  return this.http.post("someurl", {header: new HttpHeaders("cookieName", this.getCookie("cookieName")});
}

private getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Hope it will help

Sandip Jaiswal
  • 3,428
  • 2
  • 13
  • 15