问题
Why can't I access ALL headers in Angular2 from the response?
I have a legacy webservice which I can't modify. It sends some i,mportant information back to the client in the Response headers. Don't ask me why. this is crap.
my code is this:
.subscribe((r: Response) => {
var customHeader = r.headers.get("Database-Deleted");
var allHeadersAsString = JSON.stringify(r.headers);
but seems the response contains only a few headers, not all of them.
Can someone tell me this is by design and there is no way to access them? (or even better: tell me how to make it work)
UPDATE
Thanks top the comments I was able to identify it as a CORS issue. The accepted answers of other questions did not give me the right clue.
THANKS!
回答1:
It is indeed a CORS issue. Thank you n00dl3 for you comment!
If the server, in this case a C# WebAPI allows explicitly to expose the custom headers, then Angular2 allows me to access them.
This website helped me: http://datawalke.com/c/webapi-owin-cors-and-custom-headers/
Solution
For testing I was able to allow all origins and list the custom headers I need.
var att = new EnableCorsAttribute("*", "*", "*");
att.ExposedHeaders.Add("Database-Deleted");
att.ExposedHeaders.Add("Database-AlreadyDeleted");
att.ExposedHeaders.Add("Database-DryRun");
att.ExposedHeaders.Add("Database-Inserted");
att.ExposedHeaders.Add("Database-Updated");
config.EnableCors(att);
回答2:
In case your back-end is ASP.net WebAPI Core, you have to do the following way
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader().WithExposedHeaders("X-Pagination");
}));
来源:https://stackoverflow.com/questions/43067069/angular2-how-to-get-custom-response-headers-cors-issue