Jonathan Anctil Jonathan Anctil - 9 months ago 51
AngularJS Question

How to get headers from a POST response with AngularJS $http

Ok, before going further, this is happening within CORS situation.

Server #1 (http://localhost:33233) is my main website where my services (SOAP, WebAPI) are hosted. I've add these lines in the Global.asax to support CORS requests:

protected void Application_BeginRequest(object sender, EventArgs e)
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
// These headers are handling the "pre-flight" OPTIONS call sent by the browser.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Accepts, Content-Type, Origin");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

Also, on that server, when I receive a request, I'm setting a session token in the header:

HttpContext.Current.Response.Headers.Set("X-SessionToken", "{...}");

Server #2 (http://localhost:41350/login) is my mobile website built with AngularJS and where I call the remote services.

During login process, I call the SingIn service (SOAP). I hit breakpoint server-side, I set the header and return the response; the roundtrip is working.

But, when I check the header from the response client-side, I get a null value.

method: 'POST',
url: 'http://localhost:33233/ws/Authentication.asmx/SignIn',
data: {...}
}).success(function(data, status, header, config) {
var mySession = header('X-TokenSession');
}).error(function(data, status, header, config){

I have check with Fiddler or Chrome DevTools, I can see the header value in network traffic.

Is it a problem the $httpProvider?

Answer Source

Finally, I've found the answer. When I return in the session token, I need to "expose" it:

HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "X-TokenSession");