[英]Response header is present in browser but not parsed by Angular $http response.headers()
在我们的Angular应用程序中,我们需要解析一些$ http的响应头。
特别是我们需要解析一些X-prefixed响应头,例如X-Total-Results: 35
。
打开浏览器开发工具的Network
选项卡并检查相对于$ http请求的资源,我验证了响应头X-Total-Results: 35
存在。
在浏览器中,X-Total-Results标头可用,但无法在Angular $ http中解析。
有没有办法在$ http中访问'raw'响应并为头文件编写自定义解析器?
$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请求,您需要允许客户端读取标头。
您的服务器需要发送此标头:
Access-Control-Expose-Headers:X-Total-Results
要在评论中回答您的问题, Access-Control-Allow-Headers
不允许根据W3规范使用通配符
使用$ httpProvider.interceptors可以拦截请求和响应
例如
$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
return {
'responseError': function (response) {
console.log(response.config);
},
'response': function (response) {
console.log(response.config);
},
'request': function (response) {
console.log(response.config);
},
};
}]);
更新:您可以在通话中检索标题信息
$http.({method: 'GET', url: apiUrl)
.then( (data, status, headers, config){
console.log('headers: ', config.headers);
console.log('results header: ', config.headers('X-Total-Results'));
// ...
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.