Angular2: how to get custom response headers (CORS

2019-07-08 02:45发布

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.

enter image description here

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!

2条回答
Juvenile、少年°
2楼-- · 2019-07-08 03:03

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");
        }));
查看更多
冷血范
3楼-- · 2019-07-08 03:07

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);
查看更多
登录 后发表回答