When working with $http
in AngularJS, it’s common to have repetitive configurations for API calls, such as setting headers, authentication tokens, and default behaviors. Instead of configuring these for each request, AngularJS provides $http.defaults
, which allows you to set global configurations for all $http
requests in your application.
1. What is $http.defaults
?
$http.defaults
is an object that holds global settings for all $http
requests. You can use it to configure:
Default headers
Base URLs
Timeout values
Authentication tokens
This helps to avoid repetition and ensures a consistent configuration across all API requests.
2. Setting Default Headers
By default, AngularJS sets some headers like Content-Type: application/json
. You can override or add new headers using $http.defaults.headers.common
.
Example: Setting a Global Authorization Header
app.run(function($http) {
$http.defaults.headers.common["Authorization"] = "Bearer my-auth-token";
});
🔹 Now, all $http
requests will automatically include this token.
Example: Setting Custom Headers for Specific Methods
app.run(function($http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.defaults.headers.get["Accept"] = "application/json";
});
🔹 POST
requests will send data as x-www-form-urlencoded
, and GET
requests will accept JSON responses.
3. Setting a Default Base URL
If your application frequently calls the same API domain, you can set a base URL to avoid repeating the same domain name in every request.
Example: Using a Global Base URL
app.run(function($http) {
$http.defaults.baseURL = "https://api.example.com";
});
🔹 Now, calling $http.get("/users")
will automatically request https://api.example.com/users
.
❗ Note: $http.defaults.baseURL
is not a built-in feature of AngularJS, but you can define a custom service to handle this.
4. Setting Default Timeout for Requests
To prevent hanging requests, you can set a timeout for all $http
requests.
Example: Setting a 10-Second Timeout
app.run(function($http) {
$http.defaults.timeout = 10000; // 10,000 milliseconds (10 seconds)
});
If a request takes more than 10 seconds, it will automatically fail.
5. Using $http.defaults
for Global Error Handling
You can set up global error handling to catch API errors in one place.
Example: Global Error Handling with $http.defaults
app.run(function($http) {
$http.defaults.transformResponse.push(function(data, headersGetter, status) {
if (status >= 400) {
console.error("API Error:", status, data);
}
return data;
});
});
This will log all errors from API responses in one place.
6. Removing a Default Setting
If you need to remove a previously set default value, set it to undefined
.
Example: Removing a Default Header
app.run(function($http) {
delete $http.defaults.headers.common["Authorization"];
});
This removes the global Authorization
header.