问题
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?
回答1:
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).
来源:https://stackoverflow.com/questions/35124266/angular2-http-response-missing-header-key-values