![]()
In AngularJS, the $http service is commonly used to make API calls. To avoid repeating configurations (like headers, authentication tokens, or base URLs) in every API request, we can use $http.defaults.
Why Use $http.defaults?
✔ Centralized API configuration (avoid redundancy).
✔ Automatically set headers for every request.
✔ Define a base URL for all API calls.
✔ Improve maintainability and consistency.
1. Setting Global Headers Using $http.defaults.headers
If all API requests need a specific header (e.g., Authorization token or Content-Type), you can set them globally.
Example: Setting Global Headers for API Requests
app.run(function($http) {
$http.defaults.headers.common['Authorization'] = 'Bearer your_access_token';
$http.defaults.headers.post['Content-Type'] = 'application/json';
$http.defaults.headers.put['Content-Type'] = 'application/json';
});
What happens here?
- The
Authorizationheader is added to all requests (GET,POST,PUT,DELETE). - The
Content-Typeis set toapplication/jsonforPOSTandPUTrequests.
2. Setting a Global Base URL for API Requests
If your API has a common base URL, you can define it once and avoid repeating it in every request.
Example: Defining a Base URL for All API Calls
app.run(function($http) {
$http.defaults.baseURL = 'https://api.example.com/v1/';
});
🔹 Problem: $http.defaults.baseURL does not work by default.
🔹 Solution: Use an interceptor to prepend the base URL.
Example: Creating an HTTP Interceptor for Base URL
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
request: function(config) {
if (!config.url.startsWith('http')) { // Avoid modifying absolute URLs
config.url = 'https://api.example.com/v1/' + config.url;
}
return config;
}
};
});
});
What happens here?
- If the request URL does not start with
http, the base URL is automatically prepended. - This works for all
$http.get(),$http.post(), etc.
3. Enabling Global API Caching Using $http.defaults.cache
If you want to cache API responses globally, set $http.defaults.cache = true.
Example: Enabling API Caching
app.run(function($http) {
$http.defaults.cache = true;
});
How it works?
- This caches all
GETrequests automatically. - For more control, use
$cacheFactory.
4. Setting Default Timeout for API Requests
To prevent hanging requests, define a global timeout.
Example: Setting a Global Timeout
app.run(function($http) {
$http.defaults.timeout = 10000; // 10 seconds
});
What happens?
- Any API request that takes longer than 10 seconds is automatically canceled.
5. Configuring Default Transformations for API Responses
AngularJS allows modifying API responses before they reach controllers.
Example: Converting All Responses to JSON Automatically
app.run(function($http) {
$http.defaults.transformResponse.push(function(response) {
return response && typeof response === 'string' ? JSON.parse(response) : response;
});
});
Why?
- Ensures all responses are properly parsed into JSON, even if the API returns raw text.
6. Full Implementation: Applying All $http.defaults Configurations
var app = angular.module('myApp', []);
app.run(function($http) {
// Global Headers
$http.defaults.headers.common['Authorization'] = 'Bearer your_access_token';
$http.defaults.headers.post['Content-Type'] = 'application/json';
$http.defaults.headers.put['Content-Type'] = 'application/json';
// Enable API Caching
$http.defaults.cache = true;
// Set Default Timeout (10 seconds)
$http.defaults.timeout = 10000;
// Transform Responses to JSON
$http.defaults.transformResponse.push(function(response) {
return response && typeof response === 'string' ? JSON.parse(response) : response;
});
});
// Interceptor for Base URL
app.config(function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
request: function(config) {
if (!config.url.startsWith('http')) {
config.url = 'https://api.example.com/v1/' + config.url;
}
return config;
}
};
});
});
Conclusion
| Feature | Example |
|---|---|
| Global Headers | Set Authorization, Content-Type |
| Base URL Handling | Use an interceptor to prepend base URL |
| Enable API Caching | $http.defaults.cache = true |
| Default Timeout | $http.defaults.timeout = 10000 |
| Transform Responses | Convert text responses to JSON |
Final Takeaway:
- Use
$http.defaultsto reduce redundant configurations. - Use interceptors to modify requests dynamically.
- Improves maintainability, performance, and consistency.
