Angular 2-从响应中获取Cookie [英] Angular 2 - Get cookie from response

查看:514
本文介绍了Angular 2-从响应中获取Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助,我正在尝试从响应中获取cookie,但我找不到办法,我对tsc和ng2还是很陌生.

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.

这是ng2 http帖子

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);
        }
    );

这是服务器的响应:

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

我很困惑,因为我无法在headers数组中看到它...

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

console.log(response)

console.log(response.headers)

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

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

谢谢!

推荐答案

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

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

首先,该cookie设置为OK,但我在错误的位置查找它.一直以来,我一直在localhost:3000域下查找它,并且cookie已正确存储在http://demo...域下,这就是正确的行为.我可以在chrome://settings/ ==>显示高级设置==>所有cookie和站点数据... ==>中并通过远程主机进行过滤,如下所示:

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:

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

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);
               });
}

感谢@All的回复和时间!

Thanks @All for your responses and time!

这篇关于Angular 2-从响应中获取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆