AngularJS $http Timeout: Diagnosing Unexpected Status -1 Errors
0 reputation · 01 Aug 2024, 14:32 UTC
0 reputation · 01 Aug 2024, 14:32 UTC
Determine why an AngularJS 1.x application’s $http requests are failing with a status of -1 and a statusText of "timeout" even though the server should respond within the configured timeframe.
34775 reputation · 02 Aug 2024, 01:28 UTC
The request exceeded the $http timeout setting (or was manually aborted via navigation or a $timeout) before a response arrived. AngularJS treats any client‑side abort or timeout as HTTP status -1 with statusText "timeout".
AngularJS internally creates a $timeout promise that, when it resolves, calls the underlying XMLHttpRequest’s abort() method. The abort causes the XHR’s onerror handler to fire, and the $http service wraps that in a rejected promise whose error object has status === -1 and statusText === "timeout".
console.log('timeout:', config.timeout)). If it is unusually low, increase it (e.g., to 0 for no timeout or a larger value) and see if the error disappears.error.status === -1 && error.statusText === 'timeout' → client‑side timeout or abort.error.status === 0 → network failure, DNS error, or CORS preflight abort.error.status >= 400 → server‑side response (e.g., 408, 504).$http interceptor to read request metadata (e.g., URL pattern, headers) and set config.timeout accordingly.performance.now()) and apply a safety factor.app.factory('timeoutInterceptor', ['$q', function($q) {
return {
request: function(config) {
// Increase timeout for large payloads
if (config.method === 'POST' && (config.data || {}).length > 100000) {
config.timeout = 30000; // 30 s
} else {
config.timeout = 10000; // default 10 s
}
return config;
}
};
}]);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('timeoutInterceptor');
}]);
If you are unsure whether the current timeout is too low, please confirm the exact timeout value (in milliseconds) set on the failing $http call. That information determines whether raising the timeout is the appropriate next step.
Use comments to ask for clarification. Post a solution as an answer.
34,775 reputation · 02 Aug 2024, 01:13 UTC
To further clarify the distinction between a configured timeout and a general network failure, it is important to note that while both may result in a status of -1 in some browser environments, the statusText is the primary differentiator.
When the AngularJS $http timeout is triggered, the service explicitly sets the statusText to 'timeout'. In contrast, a request that fails due to a browser-level abort or a sudden loss of connectivity often returns an empty string or a browser-specific error message (like 'failed') in the statusText field. To verify this behavior in a development environment:
timeout value (e.g., 10ms) and confirm error.statusText === 'timeout'.status: 0 or -1 but with a different statusText.