Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Cookie in Request Headers Angular2

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.

like image 719
Sibiraj Avatar asked Apr 13 '17 11:04

Sibiraj


People also ask

How do I add a cookie to a request header?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

Is Cookie a HTTP header?

A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using set-cookies. It is an optional header.

What is Cookies in angular?

What is Cookies in Angular? Cookies are small packages of information that can be temporarily stored/saved by your browser and websites which are using cookies for multiple things. Cookies are used in multiple requests and browser sessions and can store your account information used by authentication for example.


1 Answers

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});
}
like image 151
jberndsen Avatar answered Sep 27 '22 22:09

jberndsen