i want to get session token in response header(Set-Cookie).how can i access values in Response header ?
var headers = new Headers();
headers.append('Content-Type', 'application/json');
console.log('url',this.loginUrl)
this.http.post(this.loginUrl,
JSON.stringify({ "username": value.username, "password": value.password }),
{ headers: headers })
.map((res: Response) =>
res.json())
.subscribe((res) => {
console.log("res", res);
this.loading.hide();
if (res.message_code == "SUCCESS") {
this.nav.setRoot(HomePage, {
username: value.username,
});
} else {
let alert = Alert.create({
title: "Sign In Error !",
subTitle: 'Please Check Username or Password.',
buttons: ['Ok']
});
this.nav.present(alert);
}
}, err => {
this.loading.hide();
console.log('error', err);
});
this is my header response
One way to solve that issue is to specify from your backend which one of the pairs {key: value} of your headers you want to expose.
Using a java backend, you can add the following lines:
And now you can access this cookie element with your angular this way
More explanation here
The problem is that you map your response to its json content. Headers can be reached from the response itself. So you need to remove the
map
operator:Be careful with CORS with accessing the response headers. See this question:
As described here
You need to set permission at producer side to access headers as -
And in angular you can do this -
Check it out.
You have to expose the headers on the server-side. Some headers are allowed to access from the client, like content-type, but not all. For more details have a look at paragraph: 'Access-Control-Expose-Headers (optional)' in http://www.html5rocks.com/en/tutorials/cors/
The answer is easy, just use the Location from url inside map function
This stumped me for an hour. Although Chrome debugger shows the 'Location' header I was unable to read it in angular@4.3.3 using Microsoft.AspNetCore.Mvc 2.0.0
It turns out it was a CORS issue. The fix was a one liner in Startup.cs:
And now I can read the header in angular:
I'm not sure how Chrome can see it but angular couldn't - it's obviously still part of the actual web api response.