Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 am successfully able to post request and get success response however when I try to get Authorization header from response I always get null whether I am able to get Content-Type header. Below is my solution so far.

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)
            });            
    }

Header Helper

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 Output enter image description here

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

like image 877
Jyotish Singh Avatar asked Feb 06 '17 08:02

Jyotish Singh


2 Answers

Header was allowed but not exposed on CORS server however adding headers.add("Access-Control-Expose-Headers", "Authorization, X-Custom"); on server did the job :)

like image 103
Jyotish Singh Avatar answered Oct 31 '22 21:10

Jyotish Singh


I've been trying to find a solution and came across this

Let's say I'm using 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 4th string parameter to globally allow any additional headers:

var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*", "X-Foo, X-Bar, X-Baz");
like image 23
jarodsmk Avatar answered Oct 31 '22 23:10

jarodsmk