CORS上缺少Angular 5响应标头 [英] Angular 5 response header is missing on CORS
问题描述
在我的角度应用程序中,我需要从响应标题中检索位置数据.服务器(Nginx)配置为允许交叉原点并允许/公开标头中的位置.我可以在chrome DEV控制台中看到此内容,但在我的有角度的应用程序中,看不到标题的任何数据.
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仅返回正文.如果您想从响应本身中检索任何内容,则可以使用observe选项:
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屋!