Understanding $http.defaults and global configurations

Loading

Understanding $http.defaults and Global Configurations in AngularJS

In AngularJS, the $http service is used to communicate with remote HTTP servers, typically through AJAX requests. One of the powerful features of $http is its ability to manage global configurations and default settings for all HTTP requests made within the application. This is where $http.defaults comes into play.

$http.defaults allows you to configure default settings for all HTTP requests, including headers, timeouts, and other configurations. These global settings can save time by allowing you to avoid specifying repetitive configurations in every HTTP request.

1. What is $http.defaults?

$http.defaults is an object that holds the default configuration settings for all $http requests made in your AngularJS application. These default values are automatically applied to each HTTP request, unless overridden in a specific request.

It provides an easy way to apply global settings, such as default headers, with minimal effort across your entire application. By using $http.defaults, you ensure consistency and avoid the need to manually configure each request.

2. Common Properties of $http.defaults

Some of the common properties you can configure with $http.defaults are:

  • headers: Allows you to set default headers for HTTP requests.
  • timeout: Defines the default timeout for all HTTP requests.
  • transformRequest and transformResponse: Allows for transformation of data before it’s sent to the server or after the response is received.
  • xsrfCookieName: The name of the cookie that contains the XSRF token.
  • xsrfHeaderName: The name of the HTTP header that will contain the XSRF token.

3. Setting Default Headers

One of the most common uses of $http.defaults is to set default headers for all HTTP requests. For example, you may want to include an authorization token in the headers of all your requests.

angular.module('myApp', [])
.config(function($httpProvider) {
// Set default headers
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer my-auth-token';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
});

Here:

  • defaults.headers.common is used to set headers that will be added to all HTTP requests, regardless of method (GET, POST, etc.).
  • defaults.headers.post is specifically for POST requests.

4. Configuring Default Timeout

You can set a global timeout for all HTTP requests. The timeout specifies how long AngularJS should wait for a response before aborting the request.

angular.module('myApp', [])
.config(function($httpProvider) {
// Set default timeout (in milliseconds)
$httpProvider.defaults.timeout = 5000; // 5 seconds timeout for all requests
});

In this example, all requests will automatically be aborted if they do not receive a response within 5 seconds.

5. Setting Up Default XSRF (Cross-Site Request Forgery) Protection

AngularJS provides XSRF protection to help guard against cross-site request forgery attacks. The $http.defaults object can be used to specify which cookies and headers to use for XSRF protection.

For example, you might want to set the following default options for XSRF protection:

angular.module('myApp', [])
.config(function($httpProvider) {
// Set default XSRF cookie and header names
$httpProvider.defaults.xsrfCookieName = 'XSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
});

This configuration ensures that every HTTP request will include the XSRF token from the cookie (XSRF-TOKEN) in the header (X-XSRF-TOKEN).

6. Default Request Transformation

You can also use $http.defaults to globally transform requests before they are sent to the server. For example, you might want to serialize data or modify the request format.

angular.module('myApp', [])
.config(function($httpProvider) {
// Set up a default request transformation to convert data into JSON
$httpProvider.defaults.transformRequest = function(data) {
if (data) {
return JSON.stringify(data); // Convert data to JSON before sending it
}
return data;
};
});

This will ensure that all request data is automatically serialized into JSON before being sent to the server.

7. Default Response Transformation

Similarly, $http.defaults allows you to set up default transformations for responses. This can be helpful if you need to process or manipulate the response data globally before it is passed to the .then() or .catch() handlers.

angular.module('myApp', [])
.config(function($httpProvider) {
// Set up a default response transformation to handle response data
$httpProvider.defaults.transformResponse = function(data) {
// Perform transformation, for example, converting data to a JavaScript object
return angular.fromJson(data);
};
});

8. Overriding $http.defaults for Individual Requests

You can override any of the $http.defaults settings for a specific HTTP request by specifying them within the request configuration object. The settings defined in the specific request configuration will override the global $http.defaults.

For example, if you have a global timeout of 5 seconds but want a particular request to have a 10-second timeout:

$http({
method: 'GET',
url: '/some-endpoint',
timeout: 10000 // Overriding the default timeout for this request
})
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log('Request failed:', error);
});

9. Using $http.defaults in Real Applications

In large AngularJS applications, $http.defaults is commonly used to centralize the configuration of HTTP requests. For example, you could use $http.defaults to handle authentication tokens, set default headers, and manage timeouts globally for the entire app.

Here’s a more complex example of how $http.defaults can be configured in a real-world scenario:

angular.module('myApp', [])
.config(function($httpProvider) {
// Set default headers
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer some-token';

// Set default timeout to handle slow network requests
$httpProvider.defaults.timeout = 10000; // 10 seconds timeout

// Set default XSRF protection cookie and header
$httpProvider.defaults.xsrfCookieName = 'XSRF-TOKEN';
$httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';

// Set default response transformation
$httpProvider.defaults.transformResponse = function(data) {
// Example: If the response contains a specific field, do some processing
if (data && data.status === 'success') {
data.message = 'Request was successful';
}
return data;
};
});

Leave a Reply

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