How to get custom response header in angular 2?

2019-04-27 09:40发布

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?

2条回答
Melony?
2楼-- · 2019-04-27 10:24

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 :)

查看更多
一夜七次
3楼-- · 2019-04-27 10:37

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");
查看更多
登录 后发表回答