Set Cookie in Request Headers Angular2

心不动则不痛 提交于 2019-12-08 15:41:37

问题


I am new to angular2. My server(spring) responds authentication with a set-cookie value in its response headers.

How to set that cookie to the request headers for the next API calls?

I searched a lot, but I cannot find a suitable solution.


回答1:


Cookies are automatically attached to every call you make after it i saved for your domain. You are doing something else wrong. In case you want to create automatic mechanism for attaching auth data to REST calls, refere to this tutorial that creates custom HttpInterceptor:

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




回答2:


As part of the http.get() or http.post() methods you can specify the RequestOptionsArgs

Use the Headers in the RequestOptionsArgs to specify the auth header you need.

As a rough example, see below:

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



回答3:


In case of a CORS scenario, you will need to add the withCredentials property set to true in the RequestOptions. Below is a snippet on how I've implemented in my HTTP helper:

get(resource: string) {
  return this.http.get(`/api/${resource}`, this.getRequestOptions())
    .map(result => result.json())
    .catch(e => e.status === 401 ? Observable.throw('Unauthorized') : e.json());
}

post(resource: string, body: any) {
  return this.http.post(`/api/${resource}`, body, this.getRequestOptions())
    .map(result => result.json())
    .catch(e => e.status === 401 ? Observable.throw('Unauthorized') : e.json());
}

private getRequestOptions() {
  const headers = new Headers({
    'Content-Type': 'application/json',
  });

  return new RequestOptions({headers: headers, withCredentials: true});
}


来源:https://stackoverflow.com/questions/43390835/set-cookie-in-request-headers-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!