Javascript code...
commonApp = angular.module('commonApp')
.config(function($httpProvider){
$httpProvider.interceptors.push('myHttpInterceptor');
})
.factory('myHttpInterceptor', function($q, $window){
return {
request: function(config){
console.log('Request started'); // LOG AT REQUEST START
return config || $q.when(config);
}
};
});
I believe that the message should be logged at the beginning of an xhr request.
But I am seeing logs without xhr requests.
Am I misunderstanding the api?
Your plunkr seems to be working fine? There's a good blog post on understanding angular http interceptors you might find useful: http://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/
Related
In my efforts to setup login required to protected pages and reroute to the login page if not authorized, while using Django REST Framework and DRF-JWT, I am trying to go through the following tutorial:
https://www.octobot.io/blog/2016-11-11-json-web-token-jwt-authentication-in-a-djangoangularjs-web-app/
I am not sure what this looks like in step 3 of the front-end section.
// Add a simple interceptor that will fetch all requests and add the jwt token to its authorization header.
Can someone provide an example?
Also, my original post regarding the issues I am having setting this up in general.
Trying to get login required to work when trying to access protected pages
Thanks!
The interceptors are service factories that are registered with the
$httpProvider by adding them to the $httpProvider.interceptors array.
The factory is called and injected with dependencies (if specified)
and returns the interceptor.
The basic idea behind intercepter is that it will be called before each $http request and you could use a service to check if user is logged in and add a token or anything else that needs to be added into the header.You could also add some logic for response for each $http request, like handling the response based on status code.
Here is how you can use it in angular for adding the access token for each http request.
angular.module('myapp')
.run(['$rootScope', '$injector', function($rootScope,$injector) {
$injector.get("$http").defaults.transformRequest = function(data, headersGetter) {
if (sessionService.isLogged()) {
headersGetter()['Authorization'] = "Bearer " + sessionService.getAccessToken();
}
if (data) {
return angular.toJson(data);
}
};
});
Here is how you can use response intercepter:
angular.module('myapp')
.factory('authHttpResponseInterceptor', function($q, $location, sessionService, $http) {
return {
response: function(response) {
//some logic here
return response || $q.when(response);
},
responseError: function(rejection) {
if (rejection.status === 401) {
//some logic here
}
return $q.reject(rejection);
}
}
});
hello everyone, i'm building a web application using "angularjs" as a front-end and using "codeingniter" as a back-end, however when i request an request with angular using "$http" built in services, it returns data nicely, so my problem is that when i check if request is ajax using built in function in "codeigniter" :$this->input->is_ajax_request() the result will be not ajax request could any one help me to solve this problem thanks a lot for all
Add HTTP_X_REQUESTED_WITH header to $http requests to match what is_ajax_request() looks for as per CI docs .
You can set as defaults or on per request basis or in httpInterceptor. $http doesn't seem to use it and there is no mandatory spec for any HTTP_X*** series headers
saw this https://forum.codeigniter.com/thread-65552.html
he fix this by
dgApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
$httpProvider.interceptors.push(['$q', function($q) {
return {
request: function(config) {
if (config.data && typeof config.data === 'object') {
config.data = $.param(config.data);
}
return config || $q.when(config);
}
};
}]);
}]);
works for me tho.
I have standard functions in my frontend AngularJS 1.x application (with ui-route) which looks like the one at bottom.
My question now would be what to do if e.g. HTTP 403 appears. Is there a best practive approach how to redirect to loginpage in AngularJS.
I would be thankful for all hints in this direction.
Thanks a lot!
function getSomethingFromServer(someParameters) {
return $http.get(api_config.BASE_URL + ...', {
}).success(function(data) {
console.log('got data from server');
}).error(function(data) {
console.log('error getting data from server'); // in my case HTTP 403 appears if token is not valid any more
});
}
Take a look at the the $http service in the angular docs and in particular response interceptors - https://docs.angularjs.org/api/ng/service/$http
I have an angular application making async requests to an API service. Since a lot of the resources are protected on the API Service, I need to intercept the HTTP requests made to the service. But as far as I can see, the interceptor I have defined only intercept page load requests.
Here is an experimental setup I have come up with to illustrate my problem:
myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
response: function(response) {
console.log(response);
return response;
}
};
});
});
What I am able to see is that, the interceptor intercepts all calls except the API call as you can see from the attached screen shot showing the console output.
The console output, as you can see from the screen shot below, contains the responses logged when the partial templates have been loaded but not when the GET request was made to the API service.
Why does this happen?
Update
I have changed my setup to include all possible combinations of requests and responses now:
$httpProvider.interceptors.push(function() {
return {
request: function(request) {
console.log(request);
return request;
},
requestError: function(request) {
console.log(request);
return config;
},
response: function(response) {
console.log(response);
return response;
},
responseError: function(response) {
console.log(response);
return response;
}
};
});
Now the interceptor intercepts the message but weirdly shows the status of the caught responseError as:
status: -1
although it clearly is a 401.
Update 2
As it turns out, even 401 responses require the CORS header to be added to it. The problem came up since the REST API I was calling used Spring-CORS library which does not include CORS headers on 401 and 403 responses.
It's a cross-site domain issue because although your using localhost your API call domain is different to the UI's (port 8080 & 8081), have a read of this article for more information. You will need add this header in your webserver:
Access-Control-Allow-Origin: http://foo.example
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Morning,
I have a $http interceptor:
app.factory('Unauthed', ['$q', 'alertService',function($q,alertService) {
return {
response: function (response) {
if (response.status == 401)
alertService.error('Authentication failure.',15000);
return response || $q.when(response);
}
};
}]);
This runs fine for all requests which are going through $http but non which go through Restangular. Looking through the soure Restangular uses $http so I am not sure what is going on here?
Cheers
Maybe the order of execution matters, where are you registering restangular? Also maybe order of dependnecies of angular modules, try declaring restangular as dependency of submodules but not in main app module so that $http is already decorated when you add restangular.