Angular 2 - 从响应中获取cookie

时间:2017-02-17 05:05:49

标签: angular typescript cookies

我需要帮助,我尝试从响应中获取Cookie,但我无法找到方法,我对tsc和ng2很新。

这是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

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

console.log(response)

的结果

Response from Chrome console

console.log(response.headers)

的结果

Headers array from Chrome console

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

Cookies section in Chrome

谢谢!

2 个答案:

答案 0 :(得分:17)

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

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

enter image description here

第二次,我忘了在其余的请求标头中使用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的回复和时间!

答案 1 :(得分:1)

我假设您正在使用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()将其转换为检索和对象。

希望这会有所帮助。如果它不是你想要的东西给我一些更多的细节,我会尽力帮助。

相关问题