Reputation: 317
Right now I have a RESTful API that's returning a refreshed JWT Authorization token every time my endpoint is accessed by my AngularJS service. I want to have a user's browser save this token (as part of the session and in localStorage
) by accessing it through the response object created by $httpProvider.intercepters
. My issue is I don't know how to get to that response object. I know my browser sees the response header and all the custom values I've put in there:
I tried accessing response.headers
and response.config.headers
but neither one contained my values. Obviously the browser sees it, but how do I get to those values?
Upvotes: 0
Views: 6109
Reputation: 1233
From AngularJS, $http documentation:
You can access the headers from success and error callback like:
1) If you are making request like:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl',
// This header will be sent as a part of the request
headers: {
'name-of-header': 'header-data'
},
}).then(function successCallback(response) {
// Access the headers like
var headerData = response.headers('name-of-header');
}, function errorCallback(response) {
// Access the headers like
var headerData = response.headers('name-of-header');
});
2) Using interceptors:
// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q) {
return {
'request': function(config) {
config.headers = config.headers || {};
// Send new header
config.headers['my-header'] = 'my-header-data';
// Don't forget to return the config
return config;
},
'response': function(response) {
// Get header from response
var myHeaderData = response.headers('my-header');
// Don't forget to return response object or a promise.'
return response || $q.when(response);
}
};
});
Note: The custom headers will be visible in the same domain. However, for the cross-domain request, the server has to send Access-Control-Expose-Headers: foo-bar-header, ...
header with the header name to expose as the value and that will make the custom header visible to the $http
module. Read more about CORS. Also, read about the Access-Control-Expose-Headers and the security considerations.
Upvotes: 7
Reputation: 74
This is simple..and it can achieve by using the following methods.
function SuccessCB(response){
// securityID is response header param name.
var resheader = response.header['securityID'];
}
Upvotes: 0