简体   繁体   English

无法从Angular 4中的POST响应标头访问属性

[英]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. 我正在尝试访问从POST响应标头收到的CSRF令牌,我需要将其与应用程序中的所有其他请求一起发送回去。 I'm was able to drill down the response stream until I could access the [[Entries]] which has the "csrfpreventionsalt" token. 在访问具有[csrfpreventionsalt“令牌的[[Entries]]之前,我可以深入研究响应流。 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. 经过尝试和测试:我已经尝试使用“ get”方法访问标头,但是它不起作用。

var csrf = res.headers.get('csrfpreventionsalt'); 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. 我在SO上看到了其他问题,这些问题说您无法访问标头值,但是如果可以在控制台中访问标头,则一定可以访问令牌并将其分配给变量。

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 按照新的httpclient的角度,如果您仍然对整个Response对象感兴趣,则可以观察它

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? Angular 4.3.3 HttpClient:如何从响应的标头获取值?

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: 我在调用json()方法之后调用了get方法,基本上我可以在原始响应对象中访问它之后获得csrf值,如下所示:

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. 还要确保您已将服务的标题字段设置为Access-Control-Allow-Headers和Access-Control-Allow-Origin的“ *”。

Also add your "Access-Control-Allow-Credentials: true". 还要添加“ Access-Control-Allow-Credentials:true”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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