I need help, I\'m trying to get the cookie from the response, and I can\'t find a way, I\'m pretty new with tsc and ng2.
This is the ng2 http post
re
Well, after some research, I've found two issues from my side.
First, the cookie was set OK, but I was looking for it in the wrong place. All this time I was looking it under my localhost:3000
domain, and the cookie was stored correctly under http://demo...
domain, that, that is the proper behavior. I could see it in chrome://settings/
==> Show advanced settings ==> All cookies and site data... ==> and filtering by the remote host like following:
Second, I forgot to use withCredentials: true
in the rest of request headers also, in order to include and accept the cookie automatically.
authenticate(username: string, password: string) {
var body = `{"username":"${username}","password":"${password}"}`;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers, withCredentials: true });
return this._http
.post('http://demo...', body, options)
.subscribe(
(response: Response) => {
this.doSomething(response);
}, (err) => {
console.log('Error: ' + err);
});
}
Thanks @All for your responses and time!
I am assuming you are using the angular2 http module to contact the server which will return an observable with the server response.
You can use the response if you subscribe to it:
//...
http.post(...your content...)
.take(1) // optional: depending on your needs you could .take(x) this to just take a certain number of responses and then terminate the subscription in order to not have a "hot Observable" lying around
.subscribe(response =>{
.console.log(response);
// if I am not mistaken "response.headers" should contain the "Set-Cookie" you are looking for
});
You could also transform the observable to a Promise:
http.post(...your content...)
.toPromise()
.then(response=>{
console.log(response);
let headers = response.headers;
console.log(headers);
})
.catch(err=>console.log(err));
In certain response cases you might need to transform it using response.json() to retrieve and object.
Hope this helps. If it isn't what you are looking for give me some more details and I'll try to help.