Using $http.defaults.headers.common for global headers

Loading

In AngularJS, $http.defaults.headers.common is a way to define global HTTP headers for all HTTP requests made using the $http service. This can be useful for setting authentication tokens, content types, or other custom headers that need to be sent with every request across your application.

1. Understanding $http.defaults.headers.common

AngularJS provides a $http.defaults object that contains the headers property, which is an object that defines the default headers. Within this, you can set a common object that holds headers to be included in every HTTP request.

The common object is used for headers that will be applied to all HTTP requests, regardless of the method (GET, POST, PUT, DELETE).

2. Setting Global Headers Using $http.defaults.headers.common

You can set common headers globally for all HTTP requests made by the $http service, such as an authorization token or a custom header.

Example: Setting an Authorization Header

angular.module('myApp', [])
.config(function($httpProvider) {
// Set a global authorization header for all requests
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer YOUR_AUTH_TOKEN';
})
.controller('MainController', function($scope, $http) {
// Make a GET request
$http.get('/api/data')
.then(function(response) {
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while fetching data.';
});
});

Explanation:

  • $httpProvider.defaults.headers.common['Authorization']: This line sets an Authorization token globally for every HTTP request made by the $http service. You would replace 'Bearer YOUR_AUTH_TOKEN' with the actual token or variable that holds it.

3. Using $http.defaults.headers.common for Custom Headers

You can also use $http.defaults.headers.common to add custom headers that should be included with each HTTP request. For example, if you need to send a custom x-requested-with header, you can configure it globally.

Example: Setting a Custom Header

angular.module('myApp', [])
.config(function($httpProvider) {
// Set custom headers for all HTTP requests
$httpProvider.defaults.headers.common['x-requested-with'] = 'XMLHttpRequest';
})
.controller('MainController', function($scope, $http) {
// Make a POST request
$http.post('/api/data', { key: 'value' })
.then(function(response) {
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while submitting data.';
});
});

Explanation:

  • $httpProvider.defaults.headers.common['x-requested-with']: This sets a custom header (x-requested-with) globally for all HTTP requests made by $http.

4. Handling CORS (Cross-Origin Resource Sharing)

Sometimes, you may need to configure custom headers to handle CORS issues, especially when making requests to a server on a different domain. You can use $http.defaults.headers.common to set the appropriate headers for CORS support, like the Access-Control-Allow-Origin header.

Example: Setting CORS Headers

angular.module('myApp', [])
.config(function($httpProvider) {
// Set CORS headers for all HTTP requests
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE';
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';
})
.controller('MainController', function($scope, $http) {
// Make a GET request
$http.get('/api/data')
.then(function(response) {
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while fetching data.';
});
});

Explanation:

  • CORS Headers: These headers are often necessary when your AngularJS application is making requests to a server located on a different domain. The example configures the CORS headers globally, allowing cross-origin requests from any origin ('*').

5. Conditional Headers

You can also set headers conditionally depending on certain factors (e.g., if the user is authenticated). You can dynamically set headers by using a function that checks a condition and adds the appropriate headers.

Example: Conditionally Setting Headers Based on User Authentication

angular.module('myApp', [])
.config(function($httpProvider) {
// Conditionally set Authorization header
var userToken = getUserAuthToken(); // Assume this function returns the user's token if available
if (userToken) {
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer ' + userToken;
}
})
.controller('MainController', function($scope, $http) {
// Make a GET request
$http.get('/api/data')
.then(function(response) {
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while fetching data.';
});
});

Explanation:

  • Dynamic Header: The Authorization header is set only if a user token is available, ensuring that the header is added only for authenticated users.

6. Removing Headers

If you want to remove a specific global header after it has been set, you can delete it from the $http.defaults.headers.common object.

Example: Removing a Global Header

angular.module('myApp', [])
.config(function($httpProvider) {
// Set a global header
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer YOUR_AUTH_TOKEN';

// Later, you can remove the header if needed
delete $httpProvider.defaults.headers.common['Authorization'];
})
.controller('MainController', function($scope, $http) {
// Make a GET request without the Authorization header
$http.get('/api/data')
.then(function(response) {
$scope.data = response.data;
console.log('Data received:', response.data);
})
.catch(function(error) {
console.error('Error occurred:', error);
$scope.errorMessage = 'An error occurred while fetching data.';
});
});

Explanation:

  • Deleting Headers: The delete keyword is used to remove a global header from $http.defaults.headers.common, which will stop it from being sent with subsequent requests.

Leave a Reply

Your email address will not be published. Required fields are marked *