Set Cookie in Angular2 Request Headers

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

How to set this cookie in request headers for the following API calls?

I searched a lot, but I can not find a suitable solution.

+4
source share
3 answers

Cookies are automatically attached to each of your calls after they are stored in your domain. You are doing something else wrong. If you want to create an automatic mechanism for binding authentication data to REST calls, refer to this guide, which creates a custom HttpInterceptor:

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

+3

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);
  }
}
Hide result
+6

In the case of a CORS script, you will need to add the hasCredentials property to true in RequestOptions. Below is a snippet of how I implemented in my HTTP assistant:

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});
}
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1674739/


All Articles