Angular2:如何获取自定义响应头(CORS问题) [英] Angular2: how to get custom response headers (CORS issue)

查看:120
本文介绍了Angular2:如何获取自定义响应头(CORS问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能从响应中访问Angular2中的所有标头?

我有一个无法修改的旧版Web服务.它将在 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.

我的代码是这样:

      .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)

更新

首先,我能将其标识为CORS问题,谢谢.其他问题的公认答案并没有给我正确的线索.

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.

谢谢!

推荐答案

这确实是 CORS问题.谢谢您 n00dl3 的评论!

It is indeed a CORS issue. Thank you n00dl3 for you comment!

如果服务器(在这种情况下为C#WebAPI)允许显式公开自定义标头,则Angular2允许我访问它们.

If the server, in this case a C# WebAPI allows explicitly to expose the custom headers, then Angular2 allows me to access them.

这个网站帮助我: http://datawalke.com/c/webapi-owin-cors-and-custom-headers/

解决方案

为了进行测试,我能够允许所有来源并列出我需要的自定义标头.

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);

这篇关于Angular2:如何获取自定义响应头(CORS问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆