5 Ways to Make an HTTP Request in Javascript

There are several ways to make an HTTP request using Javascript depending on the requirements of your application. This article covers some of most popular ways.
by Josephine Loo ·

Contents

    Web development can be categorized into front-end and back-end. They can also be known as client-side and server-side. The back-end focuses on the application logic while the front-end focuses on things that users see.

    Although both types of developments are separated, they need a medium to communicate with each other. When a user is browsing a website, the client (browser) will need to make HTTP requests to the server to retrieve the data needed.

    As of 2022, 98% of the websites use Javascript on the client side for webpage behaviors. If you are doing front-end development, making an HTTP request in Javascript is something that you must learn. This article lists some of the ways you can use.

    1. XMLHttpRequest (XHR)

    XMLHttpRequest (XHR) is the underlying object used by most HTTP request libraries to interact with servers. Despite its name, XMLHttpRequest does not only retrieve XML but can also be used to retrieve any type of data including HTML, JSON, text, blob, etc.

    XMLHttpRequest is supported by all browsers. To make a request, you need to create a new instance of the XMLHttpRequest object.

    const request = new XMLHttpRequest();
    

    Although it is supported by all browsers, Internet Explorer 5 (IE5) and Internet Explorer 6 (IE6) do not use the native XMLHttpRequest object like other modern browsers. As XMLHttpRequest was first introduced in IE5 as an ActiveX control, they use ActiveXObject.

    If you need IE5 or IE6 support, you need to create an ActiveXObject:

    var request;
    
    if (window.XMLHttpRequest) {
        // for modern browsers
        request = new XMLHttpRequest();
    } else {
        // for IE6, IE5
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    

    Then, initialize an HTTP method using open() and send the request to the server. If the request contains a body, the body can be sent as the parameter of the send() method. Otherwise, send the request with null.

    request.open('GET', URL);
    request.send(null);
    

    The XMLHttpRequest is asynchronous by default, meaning you will receive a callback when the request has been received by the server and the browser can be used without interruption while waiting for a response.

    Although it’s not advisable to make synchronous requests due to performance issues, you can do so by setting the third parameter to false when it is necessary.

    request.open('GET', URL, false);
    

    For the detail of the response returned, you can read it on MDN Web Docs.

    2. Jquery Ajax

    AJAX stands for “Asynchronous JavaScript And XML”. It is a method of the jQuery library that uses XMLHttpRequest in the background to make HTTP requests. Although the underlying object is XMLHttpRequest, there are some differences.

    Jquery Ajax wraps the XMLHttpRequest into simpler jQuery methods and reduces the code required to make an HTTP request. To use it, you will need to install jQuery or import it using CDN in your Javascript file:

    <script src="https://code.jquery.com/jquery-3.6.1.js"></script>
    

    All HTTP requests that can be made using XMLHttpRequest can also be made using the $.ajax method. For example, this is a simple GET request with response handling:

    $.ajax({
      url: URL,
      method: "GET",
    }).done(function( data ) {
        if ( console && console.log ) {
          console.log( "done" );
        }
      }).fail(function() {
        alert( "error" );
      })
      .always(function() {
        alert( "finished" );
      });
    

    Alternatively, you can use the shorthand methods$.get, $.post, $.getJSON, $.getScript, and $.load.

    var jqxhr = $.get(URL, function() {
      alert( "success" );
    }).done(function() {
        alert( "done" );
      })
      .fail(function() {
        alert( "error" );
      })
      .always(function() {
        alert( "finished" );
      });
    

    The $.ajax  method and the shorthand methods return a jQuery XMLHttpRequest (jqXHR) object, which is a superset of the browser's native XMLHttpRequest object. It implements the Promise interface, hence the HTTP request is asynchronous and allows multiple callbacks.

    3. Fetch

    The Fetch API is also similar to XMLHttpRequest but with a cleaner syntax. Unlike XMLHttpRequest, you don’t need to create a new instance of the Request object to make an HTTP request to the server. You can use the global fetch() method to make a request instead, making the code much shorter and readable.

    Fetch is a Promised-based API. HTTP requests made using the fetch() method will return a Promise that resolves to a Response object. Making a request using Fetch is simple as the path to the request is the only mandatory field.

    It can be as short as the example below to make a default GET request :

    fetch(URL)
      .then((response) => response.json())
      .then((data) => console.log(data));
    

    Alternatively, you can make a request using async/await:

    var response = await fetch(URL);
    var data = await response.json();
    console.log(data);
    

    For other types of requests, you can refer to this POST request example.

    Besides JSON, the response can be resolved into various types of formats using other methods like text(), formData(), blob(), and arrayBuffer(). However, the response can only be accessed using one of the methods. For example, if you already get the data using response.json(), you can’t use response.text() for the same request.

    Another thing to take note of when using Fetch is that it won’t reject HTTP response errors from the server like 4xx and 5xx. It will only throw an error when it is network-related.

    Although Fetch is Javascript, it might not be available for some versions of Node.js. It is implemented in Node v17.5.0 onwards but it is still in an experimental phase. If you want to use Fetch for Node.js, you can use an external module like node-fetch.

    4. Axios

    Axios is one of the most popular libraries used to make HTTP requests and it works for both front-end and back-end Javascript. Similar to Fetch, it uses Promise to handle responses asynchronously.

    This is a basic example of using Axios:

    axios.get(URL)
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      })
      .finally(function () {
        console.log("finished");
      });
    

    While Fetch and Axios are both Promise-based, some of the Axios functionalities make it more convenient to use compared to Fetch, including:

    • Monitor request progress
    • Parse data to JSON automatically
    • Catch HTTP errors
    • Intercept HTTP requests
    • Wide browser support

    Instead of stringifying your object in the request body and parsing the response received to JSON, you can pass the object directly in the request and retrieve the response as JSON without the .json() intermediate step using response.data().

    axios.post(URL, {
      item: 'Item A',
      quantity: 8
    })
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
    

    5. Angular HttpClient

    Angular HttpClient is built on top of XMLHttpRequest and is only available when using the Angular framework. It is built specifically for Angular. Therefore, it is preferred over other HTTP request methods if you are using Angular.

    Unlike other methods mentioned previously, Angular HttpClient is not Promise-based. It uses the RxJS library to handle asynchronous requests and provides many options for performing HTTP requests. The response returned is called an Observable and it needs to be subscribed to get the actual data.

    //other parts of the code are ignored
    
    constructor(private http: HttpClient) { }
    
    ngOnInit() {
    
        this.http.get(URL)
            .subscribe((response) => {                          
                console.log(response)
                },(error) => {                              
                console.error('error')
            });
    }
    

    Although a general RxJS observable can return more than one value over time, an Angular HttpClient observable only emits a single value for every request.

    One of the functionalities that distinguishes this Observable-based method from other Promise-based methods is the ability to retry failed HTTP requests automatically using the retry operator. If a request fails, it will resubscribe to the Observable according to the maximum count stated before returning an error.

    this.http.get(URL)
        .pipe(
            retry(3),
            delay(1000) // optional, retry after 1 second,
        )
        .subscribe((response) => {                          
            console.log(response)
            },(error) => {                              
            console.error(error)
        });
    

    If you want to use the response as a Promise, you can also convert it from the Observable using lastValueFrom or firstValueFrom.

    lastValueFrom(observable).then((data) => {
    	 console.log(data);
    	}).catch((error) => {
    	 console.log(error)
    	})
    

    You can convert back and forth from Observable to Promise, keeping in mind that Promise lacks some features that only Observables bring.

    const observable = from(promise);
    

    Conclusion

    Although some methods are newer and some have extra functionalities, each of them has its own advantages and disadvantages. The best method to use would be the one that fits your project requirements the most.

    While deciding which method to use in your project, you can try them by building a simple project following these tutorials:

    About the authorJosephine Loo
    Josephine is an automation enthusiast. She loves automating stuff and helping people to increase productivity with automation.

    Top 5 FFmpeg GUIs to Simplify Media Manipulation

    Discover the top 5 FFmpeg GUIs to simplify media manipulation. Learn how HandBrake, Shutter Encoder, Shotcut, QWinFF, and StaxRip simplify FFmpeg through a user interface.

    How to Automatically Create Multi-Time Zone Event Posters with Node.js and Bannerbear

    Hosting online events, workshops, or webinars for a global audience? Use Bannerbear in Node.js to automatically generate event posters with the correct time zones for different regions!

    Template Set: Batch-Generate Images in Different Dimensions Using Bannerbear (Node.js)

    Ever found yourself manually resizing images for different platforms? Let’s automate that! With Bannerbear, you can easily generate images in multiple dimensions in one go. This step-by-step tutorial shows you how to use Bannerbear’s template set to create perfectly sized images for any platform.

    Automate & Scale
    Your Marketing

    Bannerbear helps you auto-generate social media visuals, banners and more with our API and nocode integrations

    5 Ways to Make an HTTP Request in Javascript
    5 Ways to Make an HTTP Request in Javascript