Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Get cookie from response

I need help, I'm trying to get the cookie from the response, and I can't find a way, I'm pretty new with tsc and ng2.

This is the ng2 http post

return this._http
    .post('http://demo...', body, { headers: headers })
    .subscribe(
        (response: Response) => {
            this.storeToken(response);
        }, (err) => {
            console.log('Error: ' + err);
        }
    );

This is the server response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With
Set-Cookie: JSESSIONID=A099CC4CA7A25DFBD12701630A7DC24C; Path=/pbcp/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Fri, 17 Feb 2017 04:08:15 GMT

32
{"status":"OK","message":"User is Authenticated."}
0

I'm confused, because I can't see it in headers array...

Result of console.log(response)

Response from Chrome console

Result of console.log(response.headers)

Headers array from Chrome console

..., but i can see it in cookies section.

Cookies section in Chrome

Thanks!

like image 629
Sebastian Ferrari Avatar asked Feb 17 '17 05:02

Sebastian Ferrari


1 Answers

Well, after some research, I've found two issues from my side.

First, the cookie was set OK, but I was looking for it in the wrong place. All this time I was looking it under my localhost:3000 domain, and the cookie was stored correctly under http://demo... domain, that, that is the proper behavior. I could see it in chrome://settings/ ==> Show advanced settings ==> All cookies and site data... ==> and filtering by the remote host like following:

enter image description here


Second, I forgot to use withCredentials: true in the rest of request headers also, in order to include and accept the cookie automatically.

authenticate(username: string, password: string) {
    var body = `{"username":"${username}","password":"${password}"}`;
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers, withCredentials: true });

    return this._http
               .post('http://demo...', body, options)
               .subscribe(
                   (response: Response) => {
                   this.doSomething(response);
               }, (err) => {
                   console.log('Error: ' + err);
               });
}

Thanks @All for your responses and time!

like image 75
Sebastian Ferrari Avatar answered Sep 20 '22 12:09

Sebastian Ferrari