如何使用 Angular 中的 $resource 访问响应 headers?
How to access response headers using $resource in Angular?
我基本上是这样调用 get
请求的:
var resource = $resource('/api/v1/categories/:id')
resource.get({id: 1}).$promise.then(function(data){
console.log(data)
})
这很好..但我如何获得响应headers?
您可以使用 transformResponse 操作 defined here 这将允许您添加 headers
$resource('/', {}, {
get: {
method: 'GET',
transformResponse: function(data, headers){
response = {}
response.data = data;
response.headers = headers();
return response;
}
}
在此处查看工作示例JSFiddle
@Martin 的回答适用于相同的域请求。所以我想在他的回答中补充一点,如果您使用跨域请求,则必须添加另一个 header 和 Access-Control-Expose-Headers: X-Blah, X-Bla
以及 Access-Control-Allow-Origin:*
header。
其中 X-Blah
和 X-Bla
是自定义 header。
此外,您不需要使用转换请求来获取 header。您可以使用此代码:
var resource = $resource('/api/v1/categories/:id')
resource.get({id: 1}, function(data, headersFun){
console.log(data, headersFun());
})
参见 this fiddle。
希望这有帮助!!!
老问题,但我认为值得一提以备将来参考。
在 angular 文档中有 'official' 解决方案:
It's worth noting that the success callback for get, query and other
methods gets passed in the response that came from the server as well
as $http header getter function, so one could rewrite the above
example and get access to http headers as:
var User = $resource('/user/:userId', {userId:'@id'});
var users = User.query({}, function(users, responseHeaders){
// ...
console.log(responseHeaders('x-app-pagination-current-page'));
});
(为清晰起见,对文档中的代码进行了轻微更新)
对于 CORS 请求,需要公开 headers,如其他答案中所述。
我基本上是这样调用 get
请求的:
var resource = $resource('/api/v1/categories/:id')
resource.get({id: 1}).$promise.then(function(data){
console.log(data)
})
这很好..但我如何获得响应headers?
您可以使用 transformResponse 操作 defined here 这将允许您添加 headers
$resource('/', {}, {
get: {
method: 'GET',
transformResponse: function(data, headers){
response = {}
response.data = data;
response.headers = headers();
return response;
}
}
在此处查看工作示例JSFiddle
@Martin 的回答适用于相同的域请求。所以我想在他的回答中补充一点,如果您使用跨域请求,则必须添加另一个 header 和 Access-Control-Expose-Headers: X-Blah, X-Bla
以及 Access-Control-Allow-Origin:*
header。
其中 X-Blah
和 X-Bla
是自定义 header。
此外,您不需要使用转换请求来获取 header。您可以使用此代码:
var resource = $resource('/api/v1/categories/:id')
resource.get({id: 1}, function(data, headersFun){
console.log(data, headersFun());
})
参见 this fiddle。 希望这有帮助!!!
老问题,但我认为值得一提以备将来参考。 在 angular 文档中有 'official' 解决方案:
It's worth noting that the success callback for get, query and other methods gets passed in the response that came from the server as well as $http header getter function, so one could rewrite the above example and get access to http headers as:
var User = $resource('/user/:userId', {userId:'@id'});
var users = User.query({}, function(users, responseHeaders){
// ...
console.log(responseHeaders('x-app-pagination-current-page'));
});
(为清晰起见,对文档中的代码进行了轻微更新)
对于 CORS 请求,需要公开 headers,如其他答案中所述。