Angular 5 response header is missing on CORS

时光总嘲笑我的痴心妄想 提交于 2020-01-04 12:18:07

问题


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

Here is my code snippet.

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

What's going wrong here?


回答1:


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

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.




回答2:


OK. There were two issues. As @Manduro pointed out, need to add observe in the angular request. Another one is I missed the comma between two header types.

https://enable-cors.org/server_nginx.html

Need to add 'always' keyword in the location config file



来源:https://stackoverflow.com/questions/48117123/angular-5-response-header-is-missing-on-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!