响应头存在于浏览器中但未被Angular $ http response.headers()解析 [英] Response header is present in browser but not parsed by Angular $http response.headers()
问题描述
在我们的Angular应用程序中,我们需要解析一些$ http的响应头。
In our Angular app, we need to parse response headers of some $http.
特别是我们需要解析一些带X前缀的响应头,例如 X-Total-Results:35
。
In particular we need to parse some X-prefixed response headers, for example X-Total-Results: 35
.
打开浏览器开发工具的网络
标签,并检查相对于$ http请求的资源,I验证响应头 X-Total-Results:35
是否存在。
Opening the Network
tab of the browser dev tools and inspecting the resource relative to the $http request, I verified that the response header X-Total-Results: 35
is present.
在浏览器中,X- Total-Results标题可用,但无法在Angular $ http中解析。
in the browser, the X-Total-Results header is available, but cannot be parsed in the Angular $http.
有没有办法在$ http中访问'raw'响应并编写我们的自定义标题的解析器?
Is there a way to access in $http the 'raw' response and write our custom parser for the header?
$http.({method: 'GET', url: apiUrl,)
.then( function(response){
console.log('headers: ', response.headers());
console.log('results header: ', response.headers('X-Total-Results'));
// ...
})
控制台输出
headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}
results header: null
推荐答案
您无法读取JavaScript标题但可以在开发人员控制台上查看的原因是因为对于CORS请求,您需要允许客户端读取标头。
The reason you can't read the header on JavaScript but you can view it on the developer console is because for CORS requests, you need to allow the client to read the header.
您的服务器需要发送此标头:
Your server needs to send this header:
Access-Control-Expose-Headers:X-Total-Results
要在评论中回答您的问题, Access-Control-Allow-Headers
根据W3 Spec
To answer your question in the comments, The Access-Control-Allow-Headers
does not allow wildcards according to the W3 Spec
这篇关于响应头存在于浏览器中但未被Angular $ http response.headers()解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!