Reputation: 3834
jQuery has a simple and efficient way to setup a common header for all its AJAX requests.
And that is:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
How can I do such a global setup in AngularJS
Upvotes: 1
Views: 3580
Reputation: 18144
You can set headers in config of your app like Milad said or you can use the http interceptor concept.
Interceptor will be called whenever an http call is initiated and interceptor will run before the actual call processes.
angular.module('yourmodule').factory('httpRequestInterceptor',
['$rootScope', function($rootScope)
{
return {
request: function($config) {
if( $rootScope.user.loginticket )
{
$config.headers['your-auth-ticket'] = $rootScope.user.loginticket;
}
return $config;
}
};
}]);
And add this into app config:
$httpProvider.interceptors.push('httpRequestInterceptor');
Upvotes: 1
Reputation: 3834
It's possible to set header for whole the application via config app module.
var app = angular.module("auth", []);
// Configure auth app
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content')
}]);
// Parent controller
app.controller("auth", function ($scope) {
// Your $http requests will have the common information above
});
Upvotes: 4