Probably a newbie's question. I am trying not to hard-code xsrfHeaderName
and xsrfCookieName
, but how to get them from $httpProvider
?
.factory('XSRFInterceptor', function($cookies) {
return {
request: function(config) {
config.headers[$httpProvider.defaults.xsrfHeaderName] =
$cookies[$httpProvider.defaults.xsrfCookieName];
return config;
}
}
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('XSRFInterceptor');
})
After trial-and-error-ed a number of things, it seems that I still need to learn more about angularjs. Appreciate a jump-start.
Yeah so i'm pretty sure you can't inject $httpProvider into a factory. I'm not sure what property you are trying to put in your headers but this is how I do this sort of thing and it works great.
app.factory('authInterceptor', ['$rootScope', '$q', '$window',
function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers.Authorization = $cookies.Authorization;
return config;
}
};
}]);
Something like that, basically just don't use $httpProvider.
As of AngularJS 1.4.3, it just needs a line of dynamic injection:
.factory('XSRFInterceptor', function($cookies, $injector) {
return {
request: function(config) {
var $http = $injector.get('$http');
var xsrfToken = $cookies.get($http.defaults.xsrfCookieName);
if (xsrfToken)
config.headers[$http.defaults.xsrfHeaderName] = xsrfToken;
return config;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.