CORS 上缺少 Angular 5 响应标头 [英] Angular 5 response header is missing on CORS

查看:34
本文介绍了CORS 上缺少 Angular 5 响应标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 angular 应用程序中,我需要从响应标头中检索位置数据.服务器 (Nginx) 配置为允许跨源并允许/公开标头中的位置.我可以在 chrome DEV 控制台中看到这一点,但在我的 angular 应用程序中,我没有看到标题的任何数据.

In my angular app, I need to retrieve Location data from the response header. The server (Nginx) is configured to allow cross origin and to allow/expose location in header. I can see this in the chrome DEV console but in my angular app, I don't see any data for the header.

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers:Location, Content-Type
Access-Control-Expose-Headers:Location, Content-Type

这是我的代码片段.

this.httpClient.post( url, {
        UserName: username,
        Password: password
      }
    )
      .subscribe(
        (res: Response) => {
          console.log(res.headers);
        },
        error => {console.log('Error occured::' + error);
        }
      );

console.log(res.headers) 返回未定义.

console.log(res.headers) returns undefined.

这里出了什么问题?

推荐答案

新的 HttpClient 默认只返回正文.如果您想从响应本身检索任何内容,您可以使用选项观察:

The new HttpClient returns only the body by default. Should you want to retrieve anything from the response itself you can use the option observe:

  this.httpClient.post(url, {
    UserName: username,
    Password: password
  }, {
    observe: 'response'
  })
  .subscribe(res => {
    console.log(res.headers.get('Location');
  }, error => {
    console.log('Error occured::' + error);
  });

您将 res 类型转换为 Response,因此 TypeScript 没有发现您的错误.最好像我的示例中那样删除类型,以便自动正确键入.

You were typecasting res to Response so TypeScript didn’t catch your error. It’s better to remove the type as in my example so it is automatically typed correctly.

这篇关于CORS 上缺少 Angular 5 响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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