How to get value in Response header Angular2

2020-02-09 01:01发布

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

enter image description here

标签: http angular
8条回答
beautiful°
2楼-- · 2020-02-09 01:27

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楼-- · 2020-02-09 01:31

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:

查看更多
叛逆
4楼-- · 2020-02-09 01:34

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楼-- · 2020-02-09 01:35

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楼-- · 2020-02-09 01:36

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

.map((data: Response) => { response.url })
查看更多
Animai°情兽
7楼-- · 2020-02-09 01:52

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.

查看更多
登录 后发表回答