Different Ways To Make Network Requests in Javascript

Different Ways To Make Network Requests in Javascript

In this article, I will be discussing the different methods to make a network request starting from the old XMLHttp browser API to the modern libraries like Axios.

Before getting into these let us understand what exactly is meant by a network request. In simple terms, a network request is a request made by a client-side application to a server for exchanging different types of resources like images, webpages, JSON etc. We are going to see three different types of methods to make a network request which includes XMLHttp, fetch and Axios. Let's try to understand each of these methods one by one.

XMLHttp

const getdata = () =>{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://reqres.in/api/products/1");
    xhr.onload = function(){
        console.log(JSON.parse(xhr.response));
    };
    xhr.send();
}
getdata()

The code consists of a simple js function making using of XMLHttp for getting data from an API endpoint. Now let's break down the code one by one. The XMLHttpRequest() object is a built-in method in the browser it initializes an XMLHttp object . The open method in the xhr object primarily takes in two arguments. An HTTP method and the URL to the resource, this method initializes a request. The onload method can be assigned a function that can be fired when the request receives some data. The data we receive will not be in JSON format, but we can parse it to JSON using the inbuild JSON object in the browser and finally the send() method sends the request to the server

This method of doing this is fine but since it's asynchronous, we can wrap the function with a promise.

const getdata = () =>{
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "https://reqres.in/api/products/1");
        xhr.onload = function(){
            resolve(JSON.parse(xhr.response));
        };
        xhr.send();
    })

}
getdata()
.then(data => {
    console.log(data);
})

This is a quite vague implementation, it doesn't handle the rejected case but I just wanted to show you that promises could be used alongside with XMLHttp requests. A common doubt you must have now is XMLHttp requests have XML in its name but we are using JSON data, this is a very genuine question, the answer to this question is we could use both JSON and XML data with XMLHttp, it was named so because XML was a common standard in earlier days. So that's all we have for XMLHttp you could read more about it in the MDN docs.

Fetch API

XMLHttp requests work fine but, but too much code for a single request, fetch simplifies this process by implementing promises under the hood so we don't have to do it manually.

fetch('https://reqres.in/api/products/1')
.then(res =>console.log(res))

Wow that was short, but there is a small problem, if you check the response body it will be a readable stream and not any form of usable data. To convert it to any other format there are methods provided by the fetch API, one of these is res.json() which will convert the response to JSON and returns another promise which can be resolved to get the data. The following code does what we have mentioned bellow

fetch('https://reqres.in/api/products/1')
.then((res)=>{
    return res.json();
})
.then(data=>{
    console.log(data);
})

you could read more about it in the MDN docs

Axios

Unlike the other two methods, we discussed above Axios is not a native browser API it's a javascript package that can either be installed using npm or used with a CDN. Let's see a sample GET request using Axios that fetches the same data as we did before

axios.get('https://reqres.in/api/products/1')
.then(res=>{
    console.log(res)
})

you can notice it does not return a readable stream instead returns the entire data, unlike the fetch API. So is that the only difference, the answer is no. Axios provide a lot of things under the hood like XSRF protection, the ability to intercept HTTP requests etc.

Conclusion

That's all for this post, hope you got a foundation on the different methods to make a network request in js so that you could practise and learn more about these soon. If you loved my content consider following me for more of these and if you need a blog post any related content do mention it in the comments