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.
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.
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? 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.
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});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With