【问题标题】:Angular 2 - Get cookie from responseAngular 2 - 从响应中获取 cookie
【发布时间】:2017-02-17 05:05:49
【问题描述】:

我需要帮助,我正在尝试从响应中获取 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);
        }
    );

这是服务器响应:

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 数组中看不到它...

console.log(response)的结果

console.log(response.headers)的结果

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

谢谢!

【问题讨论】:

  • 试试这个 res.get("set-cookie") 并告诉我
  • 对于多个 cookie 也试试这个 let resHeader: Headers = res.headers; resHeader.getAll('set-cookie');
  • 嗨@Vinay,首先,感谢您的宝贵时间。您的建议无效,因为响应没有具有该名称的标题,请参阅我编辑的帖子。
  • 尝试打印这个console.log(response);而不是 console.log(response.headers) 这将打印来自服务器的标题。并确保您从服务器发送标头。
  • @Vinay 我已根据您的要求编辑了原始帖子,谢谢。

标签: angular typescript cookies


【解决方案1】:

嗯,经过一番研究,我发现了两个问题。

首先,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);
               });
}

感谢@All 的回复和时间!

【讨论】:

  • 有了这个答案,您可以使用response.headers 访问 Set-Cookie 标头吗?
  • 不需要访问 Set-Cookie,因为它会为每个请求自动添加。所以只需设置withCredentials: true,一切都会正常
【解决方案2】:

我假设您正在使用 angular2 http 模块来联系服务器,该模块将返回一个带有服务器响应的 observable。

如果你订阅它,你可以使用它:

//...
http.post(...your content...)
 .take(1) // optional: depending on your needs you could .take(x) this to just take a certain number of responses and then terminate the subscription in order to not have a "hot Observable" lying around
 .subscribe(response =>{
      .console.log(response);
    // if I am not mistaken "response.headers" should contain the "Set-Cookie" you are looking for 
 });

您还可以将 observable 转换为 Promise:

http.post(...your content...)
  .toPromise()
  .then(response=>{
     console.log(response);
     let headers = response.headers;
     console.log(headers);
  })
  .catch(err=>console.log(err));

在某些响应情况下,您可能需要使用 response.json() 对其进行转换以检索和对象。

希望这会有所帮助。如果这不是您想要的,请给我更多详细信息,我会尽力提供帮助。

【讨论】:

  • 嗨@jparg,谢谢你的时间,我正在使用你发布的帖子,但这不起作用,因为当我检查 headers 数组时,我没有看到“设置-cookie'。请看我更新的帖子。
  • 好吧,这很奇怪。如果您尝试通过以下方式获取 cookie: headers.getAll("set cookie") 我假设您会返回一个空数组?
  • 不,我收到了null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 2017-03-05
  • 2017-07-07
  • 2016-12-07
  • 2012-10-02
相关资源
最近更新 更多