在请求标头Angular2中设置Cookie

Sib*_*raj 10 typescript angular-http angular

我是angular2的新手.我的服务器(spring)在其响应头中使用set-cookie值响应身份验证.

如何将cookie设置为下一个API调用的请求标头?

我搜索了很多,但我找不到合适的解决方案.

aar*_*ond 9

作为http.get()http.post()方法的一部分,您可以指定RequestOptionsArgs

使用Headers中的RequestOptionsArgs指定您需要的auth标头.

作为一个粗略的例子,见下文:

class PeopleComponent {
  constructor(http: Http) {  
    let customHeaders: Headers = new Headers();
    customHeaders.append('myHeaderName', 'myHeaderValue');
    
    http.get('http://my.web/service', { headers: customHeaders })	
      .map(res => res.json())
      .subscribe(people => this.people = people);
  }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*vic 5

在我为您的域保存后,Cookie 会自动附加到您进行的每次呼叫中。你在做别的事情是错误的。如果您想创建将身份验证数据附加到 REST 调用的自动机制,请参阅创建自定义 HttpInterceptor 的本教程:

https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462