Cant get headers of response in angular 5

孤街醉人 提交于 2020-08-05 07:41:25

问题


I make a post request to a server which responds with two headers that are important for the client: username and access-token. The Network Tab of the Chrome debug tool displays the following data for the response:

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.

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?


回答1:


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, i.e. access-token, username




回答2:


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



回答3:


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. 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. You need to explicitly say which header you need console.log(res.headers.get('your-header'))



来源:https://stackoverflow.com/questions/51971342/cant-get-headers-of-response-in-angular-5

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