In the modern web development landscape, interacting with APIs and servers through HTTP requests is essential. Whether you're fetching data from an API, sending data to a server, or working with third-party services, understanding how to send HTTP requests using JavaScript is crucial.

In this guide, I'll walk you through the basics of HTTP requests in JavaScript, explore different methods for making these requests, and provide practical examples to help you get started.

Understanding HTTP Requests

HTTP (Hypertext Transfer Protocol) is the foundation of any data exchange on the web. HTTP requests are messages sent by the client to a server, usually asking for information or action. There are several types of HTTP methods, but the most commonly used are:

  • GET: Requests data from a specified resource.
  • POST: Submits data to be processed to a specified resource.
  • PUT: Updates a current resource with new data.
  • DELETE: Deletes the specified resource.

Methods for Sending HTTP Requests in JavaScript

JavaScript provides several ways to send HTTP requests. Below, we'll cover the three most popular methods: XMLHttpRequest, fetch, and Axios.

1. Using XMLHttpRequest

The XMLHttpRequest object is a traditional way to interact with servers. Although it's somewhat outdated and less popular due to the rise of modern methods, it's still important to understand how it works.

Example: Sending a GET Request Using XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(JSON.parse(xhr.responseText));
    }
};

xhr.send();

In this example, we create a new instance of XMLHttpRequest, open a GET request to a test API, and send it. The onreadystatechange event handler checks if the request is complete and successful before logging the response

2. Using the fetch API

The fetch API is the modern standard for sending HTTP requests in JavaScript. It returns a Promise and is more powerful and flexible than XMLHttpRequest.

Example: Sending a GET Request Using fetch

fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

In this example, the fetch function sends a GET request to the specified URL. The response is then converted to JSON using response.json(), and the resulting data is logged. The catch block handles any potential errors.

Example: Sending a POST Request Using fetch

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        title: 'foo',
        body: 'bar',
        userId: 1,
    }),
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

Here, we're sending a POST request with a JSON payload. The method option specifies the request type, and the body contains the data to be sent.

3. Using Axios

Axios is a popular JavaScript library that simplifies making HTTP requests. It's based on Promise and provides a clean, easy-to-use API with support for many features like request cancellation and interceptors.

Installation

You can install Axios via npm:

npm install axios

Example: Sending a GET Request Using Axios

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

Example: Sending a POST Request Using Axios

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1,
})
    .then(response => console.log(response.data))
    .catch(error => console.error('Error:', error));

Axios handles HTTP requests similarly to fetch, but with a more straightforward syntax and additional features.

When to Use Each Method

  • XMLHttpRequest: Use this if you're maintaining older codebases or need compatibility with older browsers.
  • fetch: Ideal for most modern web applications, providing a powerful and native solution for HTTP requests.
  • Axios: Best for larger projects or when you need advanced features like interceptors, automatic JSON transformation, and request cancellation.

If you enjoyed this article, please give it a clap and follow me on Medium. Don't forget to follow me on Twitter @ARYANKU82946231 and subscribe to my YouTube channel DevProject for more content on web development, JavaScript, and more!

If you found value in this post, don't forget to follow me for more insights on web development, programming tips, and the latest in tech! Your support really helps — please clap for this article if you enjoyed it.

Also, stay connected:

Follow me on Twitter for quick coding tips and updates. Check out my YouTube Channel for deep dives into development projects and tutorials. Join my learning journey on Udemy and master full-stack development, TypeScript, and more! Let's level up our skills together! 👨‍💻