π§ Did you know? Over 94% of websites use JavaScript for client-side scripting, and HTTP requests power most modern app interactions! Whether you're calling an API, submitting a form, or fetching a product list, youβre using HTTP requests.
In this guide, youβll master all the ways to make and handle HTTP requests in JavaScript β from old-school XMLHttpRequest
to the modern fetch()
and power-packed Axios.
π What Are HTTP Requests?
HTTP requests let your app communicate with a server:
- π Fetch user or product data
- π Submit forms or files
- π Authenticate and authorize users
- π¦ Upload files and images
- π Sync data with databases or APIs
β‘ The Native Hero: fetch()
Introduced in ES6, fetch()
is modern, promise-based, and built into all modern browsers.
β Basic GET Request:
fetch('https://api.publicapis.org/entries')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('Fetch error:', err));
β POST Request with Headers:
fetch('https://api.example.com/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Shibam',
email: 'shibam@example.com'
})
});
π§ fetch()
Options:
Option | Description |
---|---|
method |
HTTP method like GET , POST
|
headers |
Custom headers |
body |
Data to be sent (for POST) |
mode |
CORS handling |
credentials |
Send cookies (auth tokens) |
π Axios: The Developer Favorite
Axios is a popular HTTP client used by over 27.5 million projects monthly (NPM Trends, 2024). It simplifies requests with cleaner syntax, automatic JSON parsing, and powerful features like interceptors.
β Install:
npm install axios
β Basic GET:
import axios from 'axios';
axios.get('https://api.publicapis.org/entries')
.then(response => console.log(response.data))
.catch(error => console.error(error));
β POST with Config:
axios.post('https://api.example.com/data', {
title: 'Axios Post!',
user: 'shibam'
}, {
headers: {
'Authorization': 'Bearer TOKEN'
}
});
π₯ Features:
- β Interceptors for headers, tokens, logging
- β Automatic JSON parsing
- β Error handling with response codes
- β Node.js + Browser support
π§ͺ Old-School: XMLHttpRequest
(XHR)
π Once the only option for AJAX calls, now mostly replaced by fetch
and Axios.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
π§ Use only for legacy browser support (IE11 or older).
π Modern Pattern: Async/Await
Syntactic sugar over promises for cleaner code.
async function getData() {
try {
const response = await fetch('https://api.example.com/info');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
β
Works with both fetch()
and axios
.
π Adding Query Params
Manual (Fetch):
fetch('https://api.example.com/items?category=books&page=2')
Axios-friendly:
axios.get('/items', {
params: {
category: 'books',
page: 2
}
});
π¦ Handling FormData (File Uploads)
const formData = new FormData();
formData.append('profile', fileInput.files[0]);
fetch('/api/upload', {
method: 'POST',
body: formData
});
π¨ Error Handling Like a Pro
With fetch()
:
fetch('/api/data')
.then(res => {
if (!res.ok) throw new Error('Request failed');
return res.json();
})
.catch(error => console.error(error));
With Axios:
axios.get('/api/bad-endpoint')
.catch(error => {
if (error.response) {
console.log('Server responded with:', error.response.status);
} else if (error.request) {
console.log('No response received');
} else {
console.log('Error:', error.message);
}
});
π Multiple Requests at Once
Promise.all([
fetch('/api/user'),
fetch('/api/settings')
])
.then(async ([res1, res2]) => {
const user = await res1.json();
const settings = await res2.json();
console.log({ user, settings });
});
With Axios:
const [user, settings] = await Promise.all([
axios.get('/user'),
axios.get('/settings')
]);
π Fun Dev Stats (2025 Edition)
Metric | Value |
---|---|
Websites using JavaScript | 94.7%+ (W3Techs, Jan 2025) |
Monthly Axios downloads (NPM) | 27.5 million+ (NPM Trends 2024) |
Developers preferring fetch
|
65% (StackOverflow Survey 2024) |
Average API response time (US APIs) | ~120ms (Postman State of APIs) |
Most used HTTP method | GET (78%) |
β Summary
Method | Async | Lightweight | Legacy Support | Features |
---|---|---|---|---|
fetch() |
β | β | β | Native + Promises |
Axios |
β | β (needs install) | β | Interceptors, Timeout, Nodes |
XMLHttpRequest |
β | β | β | Callback-based, verbose |
π Final Thoughts
π§ As we move further into 2025, your safest bets for making HTTP requests in JavaScript are:
- Use
fetch()
for modern, simple use-cases - Use Axios for complex apps needing interceptors, tokens, and better error handling
- Avoid
XMLHttpRequest
unless maintaining legacy systems
π Follow me on LinkedIn for more content around JavaScript, DevRel, and AI β let's connect and build together!
Top comments (0)