Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Http Response missing header key/values

I'm making an http.patch call to a REST API that is successful (Status 200) but not all the response headers key/values are being returned. I'm interested in the ETag key/value.

Here is a code snippet:

let etag:number = 0;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('If-Match', String(etag));
this.http.patch(
    'http://example.com:9002/api/myresource/',
     JSON.stringify(dto),
     {headers: headers}
)   
.subscribe(
    (response:Response) => {
        let headers:Headers = response.headers;
        let etag:String = headers.get('ETag');
        console.log(etag);
    }
);

When making the same call with a REST Client (Postman), the response header contains:

Content-Type: application/hal+json;charset=UTF-8
Date: Mon, 01 Feb 2016 05:21:09 GMT
ETag: "1"
Last-Modified: Mon, 01 Feb 2016 05:15:32 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
X-Application-Context: application:dev:9002

Is the missing response header key/values a bug? Can the issue be resolved with configuration?

like image 490
altab Avatar asked Feb 01 '16 06:02

altab


1 Answers

This isn't an Angular issue, rather a CORS one. By definition, CORS will only return six "simple" headers: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified and Pragma.

That's why you see the full set when using a REST client such as Postman, yet when calling from your Angular client, you'll only see the set limited by CORS.

To solve this, you'll need to add an Access-Control-Expose-Headers header along the following lines:

let headers = new Headers();
headers.append('Access-Control-Expose-Headers', 'etag');

let options = new RequestOptions({ headers: headers });

return this.http.get(uri, options).map(this.extractData).catch(this.catchError);

Note that you may need to augment the server side code to support the required exposed headers.

In my case (C#), I revised the EnableCors call (within WebApiConfig) to include "ETAG" in the list of exposed headers (the fourth parameter of the EnableCorsAttribute function).

like image 131
Steve S Avatar answered Sep 17 '22 15:09

Steve S