How to get value in Response header Angular2

2020-02-09 01:45发布

问题:

i want to get session token in response header(Set-Cookie).how can i access values in Response header ?

var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            console.log('url',this.loginUrl)
            this.http.post(this.loginUrl,
                JSON.stringify({ "username": value.username, "password": value.password }),
                { headers: headers })
                .map((res: Response) => 
                    res.json())
                .subscribe((res) => {
                    console.log("res", res);
                    this.loading.hide();
                    if (res.message_code == "SUCCESS") {
                        this.nav.setRoot(HomePage, {
                            username: value.username,
                        });
                    } else {
                        let alert =  Alert.create({
                            title: "Sign In Error !",
                            subTitle: 'Please Check Username or Password.',
                            buttons: ['Ok']
                        });
                        this.nav.present(alert);
                    }
                }, err => {
                    this.loading.hide();
                    console.log('error', err);

                }); 

this is my header response

回答1:

The problem is that you map your response to its json content. Headers can be reached from the response itself. So you need to remove the map operator:

this.http.post(this.loginUrl,
       JSON.stringify({ "username": value.username, "password": value.password }),
       { headers: headers })
        /*.map((res: Response) =>  // <--------------
                res.json())*/
       .subscribe((res) => {
         var payload = res.json();
         var headers = res.headers;

         var setCookieHeader = headers.get('Set-Cookie')
         (...)
       });

Be careful with CORS with accessing the response headers. See this question:

  • angular2/http get location header of 201 response


回答2:

One way to solve that issue is to specify from your backend which one of the pairs {key: value} of your headers you want to expose.

Using a java backend, you can add the following lines:

public void methodJava(HttpServletResponse response){
...
response.addHeader("access-control-expose-headers", "Set-Cookie");
}

And now you can access this cookie element with your angular this way

service(){
...
return this.http
    .get(<your url here for your backend>)
    .map(res => console.log("cookie: " + res.headers.get("Set-Cookie") )
}

More explanation here



回答3:

.map((res: Response) => { localStorage.setItem('setCookie', res.headers._headers.get("Set-Cookie")[0]); res.json() })

or you can take reference from https://angular.io/docs/ts/latest/api/http/index/Headers-class.html



回答4:

As described here

You need to set permission at producer side to access headers as -

header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Custom-header");
header("Access-Control-Expose-Headers: X-Custom-header");

And in angular you can do this -

this._http.get(url, options).toPromise()
            .then(res => {
                var data = res.headers.get('X-Custom-header');
                console.log(data);
                return res;
            })

Check it out.



回答5:

You have to expose the headers on the server-side. Some headers are allowed to access from the client, like content-type, but not all. For more details have a look at paragraph: 'Access-Control-Expose-Headers (optional)' in http://www.html5rocks.com/en/tutorials/cors/



回答6:

This stumped me for an hour. Although Chrome debugger shows the 'Location' header I was unable to read it in angular@4.3.3 using Microsoft.AspNetCore.Mvc 2.0.0

It turns out it was a CORS issue. The fix was a one liner in Startup.cs:

app.UseCors(builder =>
    builder.WithOrigins("https://mywebsite")
        .WithExposedHeaders("Location")  // <--------- ADD THIS LINE
        .AllowAnyHeader()
        .AllowAnyMethod());

And now I can read the header in angular:

this.authHttp.post('https://someapi/something', {name: 'testing'})
    .map((response: Response) => {
        // The following line now works:
        const url = response.headers.get('Location');
    });

I'm not sure how Chrome can see it but angular couldn't - it's obviously still part of the actual web api response.



回答7:

The answer is easy, just use the Location from url inside map function

.map((data: Response) => { response.url })


回答8:

Another solution with Angular 4.2.+;

Service

getProfile(data) {
   return this.httpClient
      .request(new HttpRequest("POST", this.url, {}));
}

Component

this.userService.getProfile().subscribe(
  (response: any) => {
    if (response.type === HttpEventType.Response) {
      // response.headers is here
    }
  },
  (error: HttpErrorResponse) => {
    this.showMessage("error", "An error occurred");
  }
);


标签: http angular