DEV Community

Ayako yk
Ayako yk

Posted on

Different Ways to Make HTTP Requests in JavaScript

After learning the fundamentals by reading documentation, I got my hands dirty by creating an app based on a tutorial video. Along the way, I discovered there are several methods to make HTTP requests. Today, I’ve compiled a list of different approaches using JavaScript to fully understand them practically.

  1. Fetch API
  2. Axios
  3. jQuery.ajax
  4. WebSocket API

1. Fetch API (JavaScript Built-In)
The Fetch API is a modern JavaScript method that replaces the older XMLHttpRequest. It provides a cleaner and more powerful interface for making HTTP requests and works with Promises. The fetch() method is globally available and is used to fetch resources, such as data from a server.

fetch (URL, options)
Enter fullscreen mode Exit fullscreen mode

By default, fetch() sends a GET request.
It returns a Promise that resolves to a Response object.

Example from MDN

async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }

    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.error(error.message);
  }
}

Enter fullscreen mode Exit fullscreen mode

POST Request
To send data, we need to specify the method, headers, and body in the options object.

Making POST requests(MDN)

const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    username: "example",
  }),
});

Enter fullscreen mode Exit fullscreen mode

(slightly modified)

Some features of Fetch API
CORS (Cross-Origin Resource Sharing)
By default, fetch()includes CORS mode, which allows controlled access to resources from different origins.

Credentials
The credentials option controls whether cookies or authentication data are sent with the request.

2. Axios (Third-Party Library)
Axios is a popular third-party library and easier to use than fetch(). According to the documentation,

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.
Axios

We directly define the data property for the request payload. Axios takes care of setting headers and other details automatically.

Example code of POST
(I modified the original to turn it into an arrow function.)

const axios = require('axios'); // Make a request for a user with a given ID 

axios.get('/user?ID=12345')
  .then((response) => { // handle success 
    console.log(response); 
  })
  .catch((error) => { // handle error 
    console.log(error); 
  })
  .finally(() => { // always executed 
  });

Enter fullscreen mode Exit fullscreen mode

3. jQuery.ajax (Third-Party library)
This is part of the jQuery library. It is said to be used in legacy projects, but one of the companies I worked with was using it, so I included it.

$.ajax({
    url: 'https://api.example.com/data',
    method: 'GET',
    success: function (data) {
        console.log(data);
    },
    error: function (error) {
        console.error('Error:', error);
    }
});

Enter fullscreen mode Exit fullscreen mode

4. WebSocket API (JavaScript Built-In)
The WebSocket API establishes a two-way interactive communication channel between the client and server. This is useful for real-time communication, such as chats.

Example code from MDN

// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");

// Connection opened
socket.addEventListener("open", (event) => {
  socket.send("Hello Server!");
});

// Listen for messages
socket.addEventListener("message", (event) => {
  console.log("Message from server ", event.data);
});

Enter fullscreen mode Exit fullscreen mode

The syntax for making HTTP requests varies across programming languages and libraries, such as PHP or Next.js. However, understanding the fundamentals is invaluable, as it allows you to adapt and apply these concepts effectively, regardless of the tools you use.

Top comments (0)