How to get custom response header in angular 2?

I am new to angular 2 and currently working with angular 2.2.1, in which I can successfully send a request and get an answer for success, however, when I try to get the Authorization Response header. I always get null, can I get the Content-Type header. Below is my solution for now.

service.ts login method:

login(model: LoginModel) { let requestUrl = '/someurl'; let requestPayload = JSON.stringify(model); let headers = this.getHeaders(false); // ... Set all required headers let options = new RequestOptions({ headers: headers }); // Create a request option return this.http.post(requestUrl, requestPayload, options) // ...using post request //.map((res: Response)) // ...and calling .json() on the response to return data .subscribe((res: Response) => { var payload = res.json(); var authorization = res.headers.get('Authorization'); var contentType = res.headers.get('Content-Type'); console.log(payload, contentType, authorization) }); } 

Heading Assistant

 getHeaders(isSecureAPI: boolean) { let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' }); if (isSecureAPI) { headers.append('Authorization', 'GetFromSession'); headers.append('X-UserID', 'GetFromSession'); } return headers; } 

Fiddler Track:

enter image description here

Angular Console Exit enter image description here

So, can anyone guide me, what am I possibly doing wrong?

+6
source share
2 answers

The header was allowed but not open on the CORS server, but added headers.add ("Access-Control-Expose-Headers", "Authorization, X-Custom"); on the server completed the task :)

+10
source

I tried to find a solution and came across this

Let's say I use the Microsoft Cors WebAPI 2 Nuget package , and I have the following global configuration in my WebApiConfig.cs:

 ... var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*"); config.EnableCors(corsAttr); ... 

The EnableCorsAttribute constructor accepts a fourth row parameter to globally allow any additional headers:

 var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*", "X-Foo, X-Bar, X-Baz"); 
+2
source

Source: https://habr.com/ru/post/1014722/


All Articles