checking http request with angularjs and codeigniter - angularjs

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.

Related

How to create csrf token in angular ui

I am using angular ui as a separate package and for the backend I am using laravel backend.Now if I bypass the csrf token in laravel I can handle the post request from separate angular package but for security I will have to use csrf in post requests.I am not using middleware.Can anyone help me in this regard?
Based on my knowledge: Tern off laravel default token behavior by commenting middleware line(As you already did).
Don't afraid with this because you can use jwt-auth to pass token along with the request to protecting your request/API with the middleware that comes with jwt-auth. You can get more detail from here.
You could create an API in Laravel, which return CSRF Token, such as:
Route::get('api/token', function() {
return Session::token();
});
Of course you need to add validation on the controller or middleware, etc. For example in controller:
public function list() {
if (Session::token() != $request->header('X-Csrf-Token') )
return Response::json('CSRF does not match', 400);
// Other code
}
In your angularjs code, you could get the token and register it as a constant and could be injected in all angularjs HTTPRequest to the api:
var xhRequest = new XMLHttpRequest();
xhRequest.open("GET", "api.yourdomain.com/api/token", false);
xhRequest.send(null);
app.constant("CSRF_TOKEN", xhRequest.responseText);
app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
$http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
}]);

Angularjs + interceptors + add query parameters for only http request( not html,js,css files)

I am using angularjs, In backend I check every api authenticated.
Every request should be checked the parameter access_token.
$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
return {
request : function(config) {
config.params = config.params || {};
if ($localStorage.access_token) {
config.params.access_token = $localStorage.access_token;
}
return config || $q.when(config);
},
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor');
I using this code. Its working good, but I saw in development tools(Network) the html, css, js files also added the parameters.
like.
http://localhost/webapp/views/template/left-menu.html?access_token=xxxxxxxxxxxxxxxxx
http://localhost/webapp/css/index.css?access_token=xxxxxxxxxxxxxxxxx
But I don't like to send access_token to all http request(html,css,js).
I like to send the access_token for what are have prefix api
http://localhost:9090/api/user/get?access_token=xxxxxxxxxxxxxxxxxxxxxx
//I think the solution is find the http url and grep the text api, if found means add the parameter. Don't konw this is good approach.
Please me the good approach.
I expect only backend api request only.
Also I don't expect every serive http request to add parameter.
Its possible to add common one place in config ?
You can check url:
$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
return {
request : function(config) {
var apiPattern = /\/api\//;
config.params = config.params || {};
if ($localStorage.access_token && apiPattern.test(config.url)) {
config.params.access_token = $localStorage.access_token;
}
return config || $q.when(config);
}
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor');

API-key header is not sent (or recognized). Angularjs

I'm trying to access an API with AngularJS but I get the following error:
XMLHttpRequest cannot load http://www.football-data.org/alpha/soccerseasons/398/leagueTable?callback=JSON_CALLBACK. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://purepremier.com' is therefore not allowed access.
This is my code for the service:
angular.module('PremierLeagueApp.services', []).
factory('footballdataAPIservice', function($http) {
var footballdataAPI = {};
footballdataAPI.getTeams = function() {
$http.defaults.headers.common['Auth-Token'] = 'token';
return $http.get('http://www.football-data.org/alpha/soccerseasons/398/leagueTable?callback=JSON_CALLBACK');
};
return footballdataAPI;
});
I use an authentication token (api key) to access the api, but according the API owner this API key header is not sent or recognized. Do you have any idea how I can adapt the code to make this work? thanks!
You should hide that API key before posting on a public site such as this. I would advise you regenerate your key (if possible) just in case - better safe than sorry.
Assuming your site url is 'http://purepremier.com' from the error message, the API should add a 'Access-Control-Allow-Origin' header with your site URL to allow you access. Have a look here for more information.
This is not directly related to your problem, but I notice you are setting $http defaults every time getTeams() is called. You should either set this outside of the actual function call (preferably in a run block), or just send the GET request with that header specifically applied. As the API key is specific (I assume) to that call, you may not want to be sending it to anyone and everyone, every time you make a HTTP request.
Change your factory code like this:
factory('footballdataAPIservice', function($http) {
return {
getTeams: function(){
return $http({
url:'http://www.football-data.org/alpha/soccerseasons/398/leagueTable',
headers: { 'X-Auth-Token': 'your_token' },
method: 'GET'
}).success(function(data){
return data;
});
}
}
});
Inject factory in your controller and retreive the data:
.controller('someController',function(footballdataAPIservice,$scope){
footballdataAPIservice.getTeams().then(function(data){
$scope.teams=data;
console.log($scope.teams)
});
});
Here is the working plunker
You change the Auth-Token To Authorization
$http.defaults.headers.common['Authorization'] = 'token';
Because token is send via headers using Authorization
try jsonp
angular.module('PremierLeagueApp.services', []).
factory('footballdataAPIservice', function($http) {
var footballdataAPI = {};
footballdataAPI.getTeams = function() {
$http.defaults.headers.common['Auth-Token'] = 'token';
return $http.jsonp('http://www.football-data.org/alpha/soccerseasons/398/leagueTable?callback=JSON_CALLBACK');
};
return footballdataAPI;
});

AngularJS remote client Properties share to controllers/services

I want to develop an AngularJS web client for which the REST backend may be located on a different server.
So basically I am thinking of having a property input field on the frontend where for each session I will enter the base REST url (e.g., http://localhost:8080/backend/rest/)
Is there some sort of best practice to be able to share the base url amongst all controller/factories/services in order to include it for all $http requests?
I would configure an HTTP request interceptor service that would simply prepend the value to the URL passed to the $http service. Something like the following (not tested):
// register the interceptor as a service
$provide.factory('pathPrependerInterceptor', function() {
var _path = 'http://localhost:8080/backend/rest'; // default value
return {
request: function(config) {
config.url = _path + config.url
return config;
},
setPath: function(path) {
_path = path;
}
}
});
$httpProvider.interceptors.push('pathPrependerInterceptor');
I think the bast way would be to acomplish this with the use of interceptors. You can read more about this topic in the AngularJs documentation.
The idea is to set up an interceptor that will preappend the base url to each request something like this:
var app = angular.module('MyApp',[]);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'request': function(config) {
config.url = "http://api.openweathermap.org/data/2.5/" + config.url
return config;
}
};
});
}]);
I hope you got an idea.
There is JSFiddle that incorporates this idea.
The other answers are from a more experienced bunch, so take this with a pinch of salt, but they seem like overkill to me. You're configuring an application-wide variable which needs injection. Using
module.value("baseRestUrl", ...)
lets you inject baseRestUrl wherever it's required.

AngularJS $http interceptors

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/

Resources