🧠 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: '[email protected]'
  })
});

🔧 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!