Javascript 如何使用AngularJS拦截所有http请求?
我的问题是一个更大更广泛的版本。我想截获AngularJS函数中发出的所有http请求。稍后我需要更改请求URL,然后将其传递给服务器 我该怎么做?到目前为止,我已经使用$httpProvider和$q创建了一个拦截器,但我只能截获$http请求,而不是所有的请求,例如,如果有人单击我页面上的任何href链接等。我的拦截代码是:-Javascript 如何使用AngularJS拦截所有http请求?,javascript,angularjs,angularjs-routing,Javascript,Angularjs,Angularjs Routing,我的问题是一个更大更广泛的版本。我想截获AngularJS函数中发出的所有http请求。稍后我需要更改请求URL,然后将其传递给服务器 我该怎么做?到目前为止,我已经使用$httpProvider和$q创建了一个拦截器,但我只能截获$http请求,而不是所有的请求,例如,如果有人单击我页面上的任何href链接等。我的拦截代码是:- // register the interceptor as a service myModule.factory('myHttpInterceptor', func
// register the interceptor as a service
myModule.factory('myHttpInterceptor', function ($q) {
return {
// optional method
'request': function (config) {
// do something on success
console.log("request success");
return config;
},
// optional method
'requestError': function (rejection) {
// do something on error
console.log("Request Error");
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function (response) {
// do something on success
console.log("Response received");
return response;
},
// optional method
'responseError': function (rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});
myModule.factory('myInterceptor', ['$log', function ($log) {
$log.debug('$log is here to show you that this is a regular factory with injection');
var myInterceptor = {
};
return myInterceptor;
}]);
myModule.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
}]);
拦截到其他页面的导航与拦截http请求不同。也许您想要的是拦截$location更改 通读一下这个。您可以这样做,但这取决于位置更改的位置