Angular2 Invalid Header / Http Response Header Values

I am making an http.patch call to the REST API, which is successful (Status 200), but not all keys / values โ€‹โ€‹of the response headers are returned. I'm interested in the ETag key / value.

Here is the 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 the REST (Postman) client, 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 / value header key an error? Is it possible to solve the problem using the configuration?

+8
source share
1 answer

This is not an Angular problem, but rather CORS. By definition, CORS will only return six โ€œsimpleโ€ headers: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma.

This is why you see the full set when using a REST client such as Postman, but when called from your Angular client, you will see only the set limited to CORS.

To solve this problem, you need to add the Access-Control-Expose-Headers header in 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 increase the server-side code to support the required open headers.

In my case (C #), I redefined the EnableCors call (inside WebApiConfig) to include โ€œETAGโ€ in the list of open headers (fourth parameter of the EnableCorsAttribute function).

+5
source

All Articles