Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

http - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...