Angular 2 - Get cookie from response

后端 未结 2 654
别跟我提以往
别跟我提以往 2020-12-28 17:49

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

re         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 18:33

    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:


    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!

提交回复
热议问题