Angular 2 - 从响应中获取cookie

Seb*_*ari 15 cookies typescript angular

我需要帮助,我正在尝试从响应中获取cookie,而我找不到方法,我对tsc和ng2很新.

这是ng2 http帖子

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

这是服务器响应:

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
Run Code Online (Sandbox Code Playgroud)

我很困惑,因为我在标题数组中看不到它...

的结果 console.log(response)

来自Chrome控制台的响应

的结果 console.log(response.headers)

来自Chrome控制台的标头数组

...,但我可以在cookies部分看到它.

Chrome中的Cookie部分

谢谢!

Seb*_*ari 21

好吧,经过一番研究,我发现了两个问题.

首先,cookie已设置好,但我在错误的地方寻找它.这一次我在我的localhost:3000域名下查找它,并且cookie正确存储在http://demo...域下,这是正确的行为.我可以在chrome://settings/==>显示高级设置==>所有cookie和站点数据... ==>中看到它并由远程主机过滤,如下所示:

在此输入图像描述


其次,我忘了withCredentials: true在其余的请求标题中使用,以便自动包含和接受cookie.

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);
               });
}
Run Code Online (Sandbox Code Playgroud)

感谢@All的回复和时间!

  • 有了这个答案,您可以使用`response.headers`访问Set-Cookie标头吗? (5认同)
  • 无需访问Set-Cookie,因为它会为每个请求自动添加。所以只要设置`withCredentials:true`,一切就可以正常工作 (3认同)