DEV Community

Cover image for πŸ”₯ Mastering HTTP Requests in JavaScript (2025 Guide)
SHIBAM
SHIBAM

Posted on

1

πŸ”₯ Mastering HTTP Requests in JavaScript (2025 Guide)

🧠 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));
Enter fullscreen mode Exit fullscreen mode

βœ… 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'
  })
});
Enter fullscreen mode Exit fullscreen mode

πŸ”§ 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
Enter fullscreen mode Exit fullscreen mode

βœ… Basic GET:

import axios from 'axios';

axios.get('https://api.publicapis.org/entries')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

βœ… POST with Config:

axios.post('https://api.example.com/data', {
  title: 'Axios Post!',
  user: 'shibam'
}, {
  headers: {
    'Authorization': 'Bearer TOKEN'
  }
});
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ 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();
Enter fullscreen mode Exit fullscreen mode

🧟 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);
  }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Works with both fetch() and axios.


🌐 Adding Query Params

Manual (Fetch):

fetch('https://api.example.com/items?category=books&page=2')
Enter fullscreen mode Exit fullscreen mode

Axios-friendly:

axios.get('/items', {
  params: {
    category: 'books',
    page: 2
  }
});
Enter fullscreen mode Exit fullscreen mode

πŸ“¦ Handling FormData (File Uploads)

const formData = new FormData();
formData.append('profile', fileInput.files[0]);

fetch('/api/upload', {
  method: 'POST',
  body: formData
});
Enter fullscreen mode Exit fullscreen mode

🚨 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));
Enter fullscreen mode Exit fullscreen mode

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);
    }
  });
Enter fullscreen mode Exit fullscreen mode

πŸ” 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 });
});
Enter fullscreen mode Exit fullscreen mode

With Axios:

const [user, settings] = await Promise.all([
  axios.get('/user'),
  axios.get('/settings')
]);
Enter fullscreen mode Exit fullscreen mode

πŸ“Š 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!

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

πŸ‘‹ Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay