简体   繁体   中英

Can't access property from POST response headers in Angular 4

I'm trying to access CSRF Token received from POST response header, which I need to send back with every further request from my app. I'm was able to drill down the response stream until I could access the [[Entries]] which has the "csrfpreventionsalt" token. It gets displayed in console but when trying to access it shows as undefined.

Tried & Tested: I've tried the "get" method to access the header but it didn't work.

var csrf = res.headers.get('csrfpreventionsalt');

I've seen other questions on SO which say that you can't access the header value but If I can access the header in console then definately I should be able to access the token & assign it to a variable.

Solution to this might help others as well who could face the same situation in their apps. Any help is welcome !!

在此处输入图片说明 在此处输入图片说明

you need to map your response to get method like

this.http.get('…', { observe: 'response' });

as per new httpclient in angular, if you're still interested in the whole Response object you can observe for it

please check here

You can try the following :

 Map.forEach((value: boolean, key: string) => { console.log(key, value); }); 

I believe this question has already been asked on SO check this out

Angular 4.3.3 HttpClient : How get value from the header of a response?

I would have just put this in a comment but I don't have enough clout to comment just yet sorry

I was calling the get method after calling the json() method, basically I could get the csrf value after accessing it in the raw response object like below:

private extractLoginData = (res: Response) => {
    this.csrfToken = res.headers.get('csrfPreventionSalt');
    let body = res.json();
    return body;
}

Also make sure that you have your service has set the header fields as "*" for Access-Control-Allow-Headers & Access-Control-Allow-Origin.

Also add your "Access-Control-Allow-Credentials: true".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM