[英]Cant get headers of response in angular 5
I make a post request to a server which responds with two headers that are important for the client: username and access-token.我向服务器发出一个 post 请求,该请求响应两个对客户端很重要的标头:用户名和访问令牌。 The Network Tab of the Chrome debug tool displays the following data for the response:
Chrome 调试工具的网络选项卡显示以下响应数据:
I also log the response on the console:我还在控制台上记录了响应:
Here the headers are not present - why is this?这里没有标题 - 为什么会这样? My code for logging:
我的日志代码:
this.usersService.registerNewUser(firstName, lastName, email, username, birthday, password).subscribe(
res => {
console.log(res);
},
err => {
console.log("Error" + JSON.stringify(err));
}
);
I wanted to access the header username by res.headers.username
.我想通过
res.headers.username
访问标题用户名。
My request looks like this:我的请求是这样的:
this.http.post<string>(
"http://localhost:2002/users",
JSON.stringify({
firstName: firstName,
lastName: lastName,
email: email,
username: username,
birthday: birthday,
password: password
}),
{
observe: "response"
}
);
What have I done wrong?我做错了什么?
The front end will not be able to access that header unless the back end allows it.除非后端允许,否则前端将无法访问该标头。
In order to do so, you need to send a Access-Control-Expose-Headers
header from the backend, and the value should be a comma separated list of the values you want to expose, ie access-token, username
为此,您需要从后端发送一个
Access-Control-Expose-Headers
标头,该值应该是要公开的值的逗号分隔列表,即access-token, username
normally the response is just the 'body', while you want the 'headers'.通常,响应只是“正文”,而您需要“标题”。 on the res you could use:
在资源上你可以使用:
this.header = res.headers.get('header-name');
Just want to give additional info.只是想提供额外的信息。 Yesterday spent on this few hours and was getting crazy.
昨天花了几个小时,变得疯狂。
Once you have access-control-expose-headers
from backend.一旦您从后端
access-control-expose-headers
。 And if you just printing response object like this console.log(res)
or console.log(res.headers)
it will not show the headers because Angular uses Lazy-loading.如果你只是打印像这样的
console.log(res)
或console.log(res.headers)
这样的响应对象,它不会显示标题,因为 Angular 使用延迟加载。 You need to explicitly say which header you need console.log(res.headers.get('your-header'))
您需要明确说明您需要哪个标题
console.log(res.headers.get('your-header'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.