Most Common Ways to Make HTTP Requests in JavaScript
Tags: programming, javascript, webdev, node
Published: 2023-04-14 22:27:30

---
title: Most Common Ways to Make HTTP Requests in JavaScript
published: true
date: 2023-04-09 21:32:12 UTC
tags: Programming,Javascript,WebDevelopment,NodeJS
canonical_url: https://livecodestream.dev/post/http-requests-in-javascript/
---

 ![Live Code Stream - Programming | Career | Freelancing](https://livecodestream.dev/post/http-requests-in-javascript/featured_hu4319d5ff4a4e9c05cba253c9f6e69f4d_106557_600x0_resize_q90_h2_lanczos.webp)

In modern web development, one of the most important aspects is the ability to communicate with servers and other resources to fetch or send data. HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web, and it allows clients (such as web browsers) to request and receive data from servers. As a web developer, understanding how to make HTTP requests is essential for creating dynamic and interactive web applications.

JavaScript, the most widely used programming language for client-side web development, provides several ways to make HTTP requests. These methods enable web applications to interact with servers, APIs, and other resources, facilitating the exchange of data in various formats, such as JSON, XML, or plain text.

In this article, we will explore the most common ways to make HTTP requests in JavaScript, including XMLHttpRequest, Fetch API, Axios, and jQuery Ajax. We will discuss their usage, syntax, and advantages, as well as potential limitations and browser support. This knowledge will help you choose the most suitable method for your projects and expand your skillset as a web developer.

Let’s get started!

Useful tutorials, guides, and career tips for developers, delivered once a week.

Subscribe and get a FREE copy of my book **ten learning strategies**.

<script src="https://f.convertkit.com/ckjs/ck.5.js"></script><form action="https://app.convertkit.com/forms/3469011/subscriptions" method="post" data-sv-form-label="10 tips for the self-taught developer cta" data-sv-form="3469011" data-uid="07967a73ed" data-version="5" data-options='{"settings":{"after_subscribe":{"action":"message","success_message":"Success! Now check your email to confirm your subscription.","redirect_url":""},"analytics":{"google":null,"fathom":null,"facebook":null,"segment":null,"pinterest":null,"sparkloop":null,"googletagmanager":null},"modal":{"trigger":"timer","scroll_percentage":null,"timer":5,"devices":"all","show_once_every":15},"powered_by":{"show":true,"url":"https://convertkit.com/features/forms?utm_campaign=poweredby&amp;utm_content=form&amp;utm_medium=referral&amp;utm_source=dynamic"},"recaptcha":{"enabled":false},"return_visitor":{"action":"show","custom_content":""},"slide_in":{"display_in":"bottom_right","trigger":"timer","scroll_percentage":null,"timer":5,"devices":"all","show_once_every":15},"sticky_bar":{"display_in":"top","trigger":"timer","scroll_percentage":null,"timer":5,"devices":"all","show_once_every":15}},"version":"5"}' min-width="400 500 600 700 800">
                    <div data-style="clean">
                        <ul data-element="errors" data-group="alert"></ul>
                        <div data-element="fields" data-stacked="false">
                            <div>
                                <input name="email_address" aria-label="Email Address" placeholder="Email Address" required="" type="email">
                            </div>
                            <div>
                                <button data-element="submit">
                                    <div>
                                        <svg viewbox="0 0 24 24">
                                            <circle fill="none" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                            <path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                        <span>Sending...</span>
                                    </div>
                                    <span>
                                        DOWNLOAD THE FREE EBOOK
                                    </span>
                                </button>
                            </div>
                        </div>
                    </div>
                </form>

* * *

## Fetch API [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#fetch-api)

The [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) is a modern and powerful alternative to XMLHttpRequest for making HTTP requests in JavaScript. Introduced as a native feature in modern browsers, the Fetch API is designed to be more concise, readable, and easier to use than its predecessor. It is built on top of the Promises API, which simplifies the process of handling asynchronous operations and managing complex workflows.

One of the key advantages of the Fetch API is its native support for making requests outside the same-origin policy using CORS (Cross-Origin Resource Sharing). This enables web applications to interact with resources hosted on different domains more easily and securely.

Following a promise-based syntax, we can use Fetch to send HTTP requests from the client-side, as this example shows.

```
fetch("https://world.openfoodfacts.org/category/pastas/1.json")
  .then(response => {
    // indicates whether the response is successful (status code 200-299) or not
    if (!response.ok) {
      throw new Error(`Request failed with status ${reponse.status}`)
    }
    return response.json()
  })
  .then(data => {
    console.log(data.count)
    console.log(data.products)
  })
  .catch(error => console.log(error))

```

Fetch significantly reduces the complexity and verboseness of the code with the use of simpler syntax and promises. In this implementation, we have to use the `response.ok` field to check whether the response contains an HTTP error or not because the errors caught in the catch method belong to the network level, not the application level.

The fetch method accepts a configuration object as the second parameter to allow easy manipulation of HTTP fields like headers, content-types, the request method, etc. You can find the complete list of configuration options Fetch supports in its [official documentation](https://developer.mozilla.org/en-US/docs/Web/API/fetch).

Making POST requests with Fetch also follows a similar pattern to the previous example. Here, we use the config object to specify the request method and pass data that needs to be posted.

Let’s try this implementation using async/await:

```
async function postData () {
  const food = {
    name: "Bread",
    weight: 450,
    quantity: 3
  }

  const response = await fetch("/food", {
    method: "POST",
    body: JSON.stringify(food),
    headers: {
      "Content-Type": "application/json"
    }
  })

  if (!response.ok) {
    throw new Error(`Request failed with status ${reponse.status}`)
  }
  console.log("Request successful!")
}

```

### Pros of Fetch API [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#pros-of-fetch-api)

- Modern, concise, and more readable syntax based on Promises, making it easier to use and understand compared to XMLHttpRequest.
- Native support for making requests outside the same-origin policy using CORS, which simplifies interactions with resources hosted on different domains.
- Built-in error handling with the catch method, allowing for improved error handling capabilities in web applications.
- Provides additional features over XMLHttpRequest such as integrating Request and Response objects with the native Cache API and [sending no-cors requests](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode).
- Natively supported in modern browsers, eliminating the need for additional libraries.

### Cons of Fetch API [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#cons-of-fetch-api)

- Lacks some useful features supported by XMLHttpRequest such as aborting a request and monitoring request progress. (However, it allows the use of a separate [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) object to control request aborts and timeouts.)
- Accepts a response even when an HTTP error occurs. We have to manually check for HTTP errors and handle them.
- No built-in progress monitoring for requests, which can be useful for tracking the progress of large file uploads or downloads.

* * *

## Axios [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#axios)

[Axios](https://github.com/axios/axios) is a popular and widely used JavaScript library for making HTTP requests. It offers a simple, clean, and easy-to-use API based on Promises, making it an attractive choice for developers who prefer a more readable and concise syntax compared to XMLHttpRequest. Unlike the Fetch API, Axios works seamlessly in both browser and Node.js environments, making it a versatile solution for various types of projects.

The library provides a range of advanced features and built-in functionality, such as error handling, request cancellation, and interceptors, which can be used to modify requests and responses globally or on a per-request basis. Additionally, Axios automatically transforms JSON data, simplifying the process of sending and receiving data in a common format.

When making GET requests with Axios, we can use the dedicated `axios.get()` method to compile the request. Here we’ve shown an example of the implementation:

```
axios.get("https://world.openfoodfacts.org/category/pastas/1.json")
  .then(response => {
    // access parsed JSON response data using response.data field
    data = response.data
    console.log(data.count)
    console.log(data.products)
  })
  .catch(error => {
    if (error.response) {
      //get HTTP error code
      console.log(error.reponse.status)
    } else {
      console.log(error.message)
    }
  })

```

As this example shows, Axios reduces the amount of work we have to do on our end to make HTTP requests even compared to Fetch. It automatically parses the received JSON data, which we can access through response.data field. Axios also catches HTTP errors in its catch method, removing the need to specifically check for status code before processing the response. Inside the catch method, we can distinguish HTTP errors using an error.response check, which stores the HTTP error code.

For sending POST requests with Axios, we use the dedicated `axios.post()` method as the following example, implemented using async/await, shows:

```
async function postData () {
  const food = {
    name: "Bread",
    weight: 450,
    quantity: 3
  }

  try {
    const response = await axios.post("/food", food)
    console.log("Request successful!")
  } catch (error) {
    if (error.response) {
      console.log(error.reponse.status)
    } else {
      console.log(error.message)
    }
  }
}

```

Again, Axios simplifies this implementation by automatically converting Javascript objects to JSON without our interception. These Axios methods also accept a final parameter specifying HTTP configurations.

Other than these basic features, Axios provides solutions for many unique use cases that we won’t discuss here. But if you want to dive deeper into working with Axios in Javascript as well as Node.js, you can follow this [in-depth guide to Axios](https://livecodestream.dev/post/how-to-master-http-requests-with-axios/) on our blog.

### Pros of Axios [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#pros-of-axios)

- Easy-to-use and concise syntax based on Promises, offering a more readable and intuitive experience compared to XMLHttpRequest.
- Built-in support for error handling and request cancellation, which simplifies the process of managing complex requests and improving the user experience.
- Supports both browser and Node.js environments, making it a versatile solution for various types of projects and platforms.
- Provides useful features like interceptors for modifying requests and responses globally or on a per-request basis, and automatic JSON data transformation.
- Rejects on HTTP errors by default, making error handling more intuitive than the Fetch API.

### Cons of Axios [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#cons-of-axios)

- Requires an additional library to be added to your project, which can increase the overall size of the application.

* * *

## XMLHttpRequest [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#xmlhttprequest)

[XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) is a native API in Javascriptthat has been around since the early 2000s. It was initially developed by Microsoft and later adopted by other browsers. Although the name suggests that it is specifically designed for XML data, XMLHttpRequest can be used to request and handle a variety of data formats, such as JSON, HTML, and plain text.

Over the years, XMLHttpRequest has become a fundamental building block for making asynchronous HTTP requests in web applications. However, its usage has somewhat declined with the introduction of more modern and easier-to-use alternatives, such as the Fetch API.

Here’s how we can send GET requests and asynchronously retrieve data from a remote API using XMLHttpRequest API:

```
//create XMLHttpRequest object
const xhr = new XMLHttpRequest()
//open a get request with the remote server URL
xhr.open("GET", "https://world.openfoodfacts.org/category/pastas/1.json")
//send the Http request
xhr.send()

//EVENT HANDLERS

//triggered when the response is completed
xhr.onload = function() {
  if (xhr.status === 200) {
    //parse JSON datax`x
    data = JSON.parse(xhr.responseText)
    console.log(data.count)
    console.log(data.products)
  } else if (xhr.status === 404) {
    console.log("No records found")
  }
}

//triggered when a network-level error occurs with the request
xhr.onerror = function() {
  console.log("Network error occurred")
}

//triggered periodically as the client receives data
//used to monitor the progress of the request
xhr.onprogress = function(e) {
  if (e.lengthComputable) {
    console.log(`${e.loaded} B of ${e.total} B loaded!`)
  } else {
    console.log(`${e.loaded} B loaded!`)
  }
}

```

As this example shows, the process of sending a GET request with XMLHttpRequest involves three steps:

- Create XMLHttpRequest
- Opening the HTTP request of the indented type
- Sending the request

Once the request is sent, we can use the event handlers provided by the XMLHttpObject to handle its response. Here, we have used two event handlers: `onload`, `onerror`, and `onprogress`. It’s important to note here that onerror method only handles network-level errors related to the request. To identify HTTP errors, we have to check the HTTP status code inside the onload method specifically.

We can send POST requests with XMLHttpRequest following a similar pattern.

```
// create XMLHttpRequest object
const xhr = new XMLHttpRequest()
// open a POST request
xhr.open("POST", "/food")
// set content-type header to JSON
xhr.setRequestHeader("Content-Type", "application/json");
// send JSON data to the remote server
xhr.send(JSON.stringify(food))

// Event Handlers

// track data upload progress
xhr.upload.onprogress = function(e) {
  console.log(`${e.loaded}B of ${e.total}B uploaded!`)
}

// triggered when data upload is finished
xhr.upload.onload = function(e) {
  console.log("Upload completed")
}

// triggered when the response is fully received
xhr.onload = function() {
  console.log(xhr.status)
}

// triggered due to a network-level error
xhr.onerror = function() {
  console.log("Network error occurred")
}

```

One main difference between the earlier GET and the current POST request is explicitly setting the content-type headers when posting JSON data. Also, there is an additional event type a POST request can trigger compared to a GET request. They are upload events accessed through the xhr.upload field. These event handlers help us track the data upload progress when the request body has to carry a significant amount of data (e.g., images, files, etc.)

### Pros of XMLHttpRequest [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#pros-of-xmlhttprequest)

- Excellent browser support, including older browsers like Internet Explorer 7 and above.
- Removes the need for external dependencies.
- Ability to monitor the progress of a request using the readystatechange event.

### Cons of XMLHttpRequest [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#cons-of-xmlhttprequest)

- Verbose and less intuitive syntax compared to modern alternatives.
- No support for async/await or promise-based syntax.
- Lacks some advanced features and error handling capabilities found in newer APIs.

* * *

## JQuery Ajax [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#jquery-ajax)

jQuery is a widely used and popular JavaScript library that simplifies various aspects of web development, such as DOM manipulation, event handling, and animation. One of its powerful features is jQuery Ajax, which provides a simple and easy-to-use API for making asynchronous HTTP requests. jQuery Ajax has been a popular choice among web developers for many years due to its simplified syntax and ease of use compared to XMLHttpRequest.

The jQuery Ajax API offers several advanced features and options, such as error handling, timeout settings, caching, and support for JSONP (JSON with Padding) to work around cross-domain request limitations. These features make it an attractive option for developers who are already using jQuery in their projects or prefer a more simplified approach to making HTTP requests.

Though it is from the pre-framework (like React, angular, etc) era, it is still adopted by many websites, specially when working with platforms such as wordpress and templates.

Let’s see an example of a GET request with jQuery:

```
$.ajax({
  url: 'https://world.openfoodfacts.org/category/pastas/1.json',
  method: 'GET',
  dataType: 'json',
  success: function(data) {
    // Handle the received data
    console.log(data);
  },
  error: function(xhr, status, error) {
    // Handle any errors
    console.error('Error: ' + status + ' - ' + error);
  }
});

```

Similarly, you can have a post request:

```
$.ajax({
  url: 'https://world.openfoodfacts.org/category/pastas/1.json',
  method: 'POST',
  dataType: 'json',
  data: json,
  success: function(data) {
    // Handle the received data
    console.log(data);
  },
  error: function(xhr, status, error) {
    // Handle any errors
    console.error('Error: ' + status + ' - ' + error);
  }
});

```

### Pros of jQuery Ajax [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#pros-of-jquery-ajax)

- Simplified syntax and ease of use, making it more accessible for developers compared to XMLHttpRequest.
- Provides advanced features and options like error handling, timeout settings, caching, and JSONP support for cross-domain requests, which can improve the overall user experience.
- Widely adopted and popular due to the extensive use of the jQuery library in the web development community, ensuring a wealth of resources and support.

### Cons of jQuery Ajax [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#cons-of-jquery-ajax)

- Requires the inclusion of the jQuery library, which may not be needed for other parts of the project, adding extra weight and complexity to the application.
- Less relevant and less frequently used in modern web development due to the rise of alternative libraries and native APIs like Fetch and Axios, which offer similar functionality without the need for jQuery.
- Not as lightweight and performant as native APIs like Fetch or XMLHttpRequest, which might be a concern for performance-sensitive projects or applications targeting slow connections or limited resources.

* * *

## Ky [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#ky)

[Ky](https://github.com/sindresorhus/ky) is a relatively new Javascript package that can be used for making asynchronous HTTP requests from the front end of a web application. It’s built on top of the native Fetch API with a simpler syntax and additional functionality.

Ky provides a simple syntax for making requests with its dedicated HTTP methods. Here’s an example of sending a GET request using Ky with async/await.

```
async function getData () {
  try {
    const data = await ky.get("https://world.openfoodfacts.org/category/pastas/1.json").json()
    console.log(data.count)
    console.log(data.products)
  } catch (error) {
    if (error.response) {
      console.log(error.response.status)
    } else {
      console.log(error.message)
    }
  }
}

```

We can send POST requests following a similar pattern:

```
async function postData () {
  try {
    const response = await ky.post("/food", { json: food })
    console.log("Request successful!")
  } catch (error) {
    if (error.response) {
      console.log(error.reponse.status)
    } else {
      console.log(error.message)
    }
  }
}

```

### Pros of Ky [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#pros-of-ky)

- Gives a simple, lightweight, promise-based API for making HTTP requests.
- Addresses some limitations in the native Fetch API with support for features like request timeout, retry, and monitoring progress.
- Provides hooks for modifying requests during their lifecycle: beforeRequest, afterResponse, beforeRetry, etc.
- Supports all modern browsers like Chrome, Firefox, Safari. For Internet Explorer support, Ky provides an alternative package, [Ky-Universal](https://github.com/sindresorhus/ky-universal), not sure why they still bother.

### Cons of Ky [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#cons-of-ky)

- Relatively a new package compared to other mature, versatile options discussed in this post. Adds an external dependency.

* * *

## Conclusion [<svg height="22" viewbox="0 0 24 24" width="22" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"></path><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path></svg>](#conclusion)

n conclusion, there are several methods available for making HTTP requests in JavaScript, each with its own advantages and disadvantages. Choosing the right method for your project depends on various factors, such as browser support, ease of use, performance, and the specific requirements of your application.

In this article we explored, XMLHttpRequest, Axios, Fetch API, jQuery Ajax, and Ky with examples, pros and cons. By now you should be able to evaluate the specific needs of your project, and choose the most suitable approach for making HTTP requests in JavaScript, ensuring efficient and responsive web applications with improved error handling and versatile functionality.

**Note: Nowadays I almost always go with Axios or FetchAPI**

Thanks for reading!

**Newsletter**  
  
[Subscribe to my weekly newsletter](https://livecodestream.dev/newsletter/) for developers and builders and get a weekly email with relevant content.