Fix: Axios Network Error — Request Failed with Status Code 0
Quick Answer
How to fix Axios 'Network Error' with no status code — CORS blocks, SSL certificate issues, request timeout, no internet connection, and debugging with interceptors.
The Error
An Axios request fails with a generic network error and no HTTP status code:
axios.get('https://api.example.com/data')
.catch(error => {
console.log(error.message); // "Network Error"
console.log(error.response); // undefined — no response received
console.log(error.code); // "ERR_NETWORK" or undefined
});Or:
AxiosError: Network Error
at XMLHttpRequest.handleError (axios/lib/adapters/xhr.js:...)Or a timeout error:
AxiosError: timeout of 5000ms exceeded
code: 'ECONNABORTED'
message: 'timeout of 5000ms exceeded'The request never reaches the server — or the server returns a response that the browser refuses to pass to JavaScript.
Why This Happens
An Axios “Network Error” with no error.response means the HTTP request didn’t complete successfully at the network level. The browser didn’t receive a readable response:
- CORS block — the browser made the request, the server responded, but the response was blocked because CORS headers were missing or wrong. The browser hides the actual response from JavaScript for security, resulting in “Network Error”.
- Request timeout — the server took longer than
timeoutmilliseconds to respond. Axios aborts the request. - No internet / DNS failure — the device has no connectivity, or the domain doesn’t resolve.
- SSL/TLS certificate error — the server’s certificate is invalid, expired, or self-signed. The browser blocks the connection.
- Mixed content — your HTTPS page makes an HTTP request. Browsers block this.
- Server completely unreachable — the server is down, the port is closed, or a firewall is blocking the connection.
- Ad blocker or browser extension — some extensions block requests to analytics, tracking, or ad domains.
Fix 1: Diagnose with the Browser Network Tab
The most important first step: open DevTools (F12) → Network tab → find the failed request.
CORS block shows:
- Status:
CORS error(in Firefox) or(failed)in Chrome - In Console:
Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy
Timeout shows:
- Request hangs for the timeout duration, then fails
error.code === 'ECONNABORTED'
SSL error shows:
- Connection blocked before any HTTP headers are exchanged
- Console:
net::ERR_CERT_AUTHORITY_INVALIDorERR_CERT_DATE_INVALID
No server shows:
net::ERR_CONNECTION_REFUSEDornet::ERR_NAME_NOT_RESOLVED
Each failure mode requires a different fix.
Fix 2: Fix CORS
CORS blocks are the most common cause of Axios “Network Error”. The request reaches the server but the browser rejects the response. Fix it on the server side by adding the correct CORS headers:
Express.js:
const cors = require('cors');
app.use(cors({
origin: 'https://app.example.com', // Allow your frontend origin
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
}));Or use a proxy in development — route requests through the same origin to avoid CORS entirely:
// vite.config.ts — proxy /api to the backend
export default {
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
};// Axios call — same-origin, no CORS
axios.get('/api/users'); // Proxied to http://localhost:8080/api/usersFor Next.js, use API routes or rewrites() in next.config.js to proxy requests server-side.
Important: CORS is enforced by the browser. Testing with curl or Postman won’t show CORS errors — only browser requests are affected. Always use the browser’s Network tab to diagnose.
Fix 3: Fix Timeout Errors
If error.code === 'ECONNABORTED', the request timed out. The default timeout in Axios is 0 (no timeout). If you set a timeout, increase it or fix the slow server:
// Check your axios instance configuration
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000, // 5 seconds — increase if your server is legitimately slow
});
// Or set per-request
axios.get('/data', { timeout: 30000 }); // 30 seconds for a slow endpointHandle timeouts explicitly:
axios.get('/api/report', { timeout: 60000 })
.catch(error => {
if (error.code === 'ECONNABORTED') {
console.error('Request timed out — server may be overloaded');
// Show user-friendly message, offer retry
} else {
throw error;
}
});Implement retry with exponential backoff:
import axios from 'axios';
import axiosRetry from 'axios-retry';
axiosRetry(axios, {
retries: 3,
retryDelay: axiosRetry.exponentialDelay, // 1s, 2s, 4s
retryCondition: (error) =>
axiosRetry.isNetworkOrIdempotentRequestError(error) ||
error.code === 'ECONNABORTED',
});Fix 4: Fix SSL Certificate Errors
If the server has an invalid, expired, or self-signed certificate, the browser blocks the connection before any HTTP response is received:
In development with a self-signed cert — configure Axios to accept it (Node.js only, never in browser):
const https = require('https');
const api = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false, // Accept self-signed certs
// WARNING: Only use this in development/testing
}),
});In production — fix the actual certificate:
# Check certificate expiry
openssl s_client -connect api.example.com:443 2>/dev/null | openssl x509 -noout -dates
# Renew with Certbot
certbot renew --force-renewalMixed content — your HTTPS page calls an HTTP endpoint. Fix by ensuring the API also uses HTTPS, or prefix-relative URLs:
// Broken — HTTP request from HTTPS page
axios.get('http://api.example.com/data'); // Blocked as mixed content
// Fixed
axios.get('https://api.example.com/data');
// Or use protocol-relative (inherits page protocol)
axios.get('//api.example.com/data'); // Uses https:// on HTTPS pagesFix 5: Add Global Error Handling with Interceptors
Use Axios interceptors to catch and categorize network errors across your entire application:
import axios from 'axios';
const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 10000,
});
// Request interceptor — add auth headers
api.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// Response interceptor — handle errors centrally
api.interceptors.response.use(
response => response,
error => {
if (!error.response) {
// Network error — no response received
if (error.code === 'ECONNABORTED') {
console.error('Request timed out');
return Promise.reject(new Error('Request timed out. Please try again.'));
}
if (!navigator.onLine) {
console.error('No internet connection');
return Promise.reject(new Error('No internet connection.'));
}
// CORS, SSL, or server unreachable
console.error('Network error:', error.message);
return Promise.reject(new Error('Unable to reach the server. Please try again.'));
}
// HTTP error responses
const { status } = error.response;
if (status === 401) {
// Token expired — redirect to login
localStorage.removeItem('token');
window.location.href = '/login';
} else if (status === 429) {
return Promise.reject(new Error('Too many requests. Please wait a moment.'));
}
return Promise.reject(error);
}
);
export default api;Fix 6: Check Connectivity Before Requests
For better UX, detect connectivity issues before making requests:
async function fetchWithConnectivityCheck(url, options = {}) {
if (!navigator.onLine) {
throw new Error('No internet connection');
}
try {
return await axios.get(url, options);
} catch (error) {
if (error.code === 'ERR_NETWORK') {
// Could be CORS, SSL, or server down — check the console
throw new Error('Network request failed. Check the browser console for details.');
}
throw error;
}
}Listen for online/offline events:
window.addEventListener('online', () => {
console.log('Connection restored');
// Retry pending requests
});
window.addEventListener('offline', () => {
console.log('Connection lost');
// Show offline indicator in UI
});Fix 7: Debug Network Errors in Node.js
In Node.js (SSR, scripts, CLI), Axios errors include more detail because there’s no browser security restricting what you see:
axios.get('https://api.example.com/data')
.catch(error => {
if (error.code === 'ECONNREFUSED') {
console.error('Server is not running or port is closed');
} else if (error.code === 'ENOTFOUND') {
console.error('DNS resolution failed — check the hostname');
} else if (error.code === 'ETIMEDOUT') {
console.error('Connection timed out');
} else if (error.code === 'CERT_HAS_EXPIRED') {
console.error('SSL certificate expired');
} else {
console.error('Error code:', error.code);
console.error('Error message:', error.message);
}
});Enable Axios debug logging in Node.js:
// Log request details
axios.interceptors.request.use(request => {
console.log('Request:', request.method?.toUpperCase(), request.url);
return request;
});
axios.interceptors.response.use(
response => {
console.log('Response:', response.status, response.config.url);
return response;
},
error => {
console.error('Error:', error.code, error.config?.url);
return Promise.reject(error);
}
);Still Not Working?
Test the endpoint directly with curl:
curl -v https://api.example.com/data \
-H "Authorization: Bearer your-token" \
-H "Origin: https://app.example.com"If curl works but Axios doesn’t, it’s CORS (browser-specific) or an extension blocking the request.
Check for ad blockers. Temporarily disable all browser extensions and retry. If it works without extensions, the request URL matches an ad-blocker rule.
Verify the base URL. A common mistake is a wrong baseURL in the Axios instance combined with a relative URL:
const api = axios.create({ baseURL: 'https://api.example.com/v1' });
// Resolves to: https://api.example.com/v1/users ✓
api.get('/users');
// Resolves to: https://api.example.com/users (note: /v1 is removed!)
api.get('users'); // Missing leading slash — resolves relative to baseURL
// Resolves to: https://other.example.com/data (ignores baseURL entirely)
api.get('https://other.example.com/data');For related issues, see Fix: Express CORS Not Working and Fix: Flask CORS Not Working.
Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.
Was this article helpful?
Related Articles
Fix: CodeMirror Not Working — Editor Not Rendering, Extensions Not Loading, or React State Out of Sync
How to fix CodeMirror 6 issues — basic setup, language and theme extensions, React integration, vim mode, collaborative editing, custom keybindings, and read-only mode.
Fix: GSAP Not Working — Animations Not Playing, ScrollTrigger Not Firing, or React Cleanup Issues
How to fix GSAP animation issues — timeline and tween basics, ScrollTrigger setup, React useGSAP hook, cleanup and context, SplitText, stagger animations, and Next.js integration.
Fix: i18next Not Working — Translations Missing, Language Not Switching, or Namespace Errors
How to fix i18next issues — react-i18next setup, translation file loading, namespace configuration, language detection, interpolation, pluralization, and Next.js integration.
Fix: ky Not Working — Requests Failing, Hooks Not Firing, or Retry Not Working
How to fix ky HTTP client issues — instance creation, hooks (beforeRequest, afterResponse), retry configuration, timeout handling, JSON parsing, error handling, and migration from fetch or axios.