How to make an HTTP request on Javascript

How to make an HTTP request on Javascript

JavaScript is a programming language that can be used on both the client-side and server side to create interactive web pages and applications. One of the most common tasks in web development is making HTTP requests to retrieve data from a server. In this article, we will explore how to make HTTP requests in JavaScript.

HTTP stands for HyperText Transfer Protocol, which is the foundation of data communication on the World Wide Web. HTTP is used to transmit data over the internet between a client, such as a web browser, and a server. An HTTP request is a message sent by the client to request data or information from the server.

There are several ways to make HTTP requests in JavaScript, but the most commonly used method is by using the XMLHttpRequest (XHR) object. The XHR object provides an easy way to send and receive data from a web server using JavaScript.

The XMLHttpRequest Object

The XMLHttpRequest object is a built-in object in JavaScript that allows us to send HTTP requests and receive responses from a web server. The XHR object is part of the window object, which means it is accessible from anywhere in your JavaScript code.

Creating an XHR Object

To create an XHR object, we use the following syntax:

var xhr = new XMLHttpRequest();

Sending an HTTP Request

Once we have created an XHR object, we can use it to send an HTTP request. We do this by calling the open() method and passing in the HTTP method, URL, and optional async flag.

xhr.open(method, url[, async]);

The HTTP method can be one of the following:

  • GET: Retrieve data from the server.

  • POST: Submit data to the server.

  • PUT: Update data on the server.

  • DELETE: Delete data from the server.

The URL is the address of the server endpoint we want to request data. The async flag is an optional parameter that indicates whether the request should be asynchronous or not. If this flag is set to true, the request will be sent asynchronously, which means that the JavaScript code will not wait for the response before continuing to execute. If the flag is set to false, the request will be sent synchronously, which means that the JavaScript code will wait for the response before continuing to execute.

Once we have called the open() method, we can send the request using the send() method.

xhr.send();

Handling the Response

After sending the request, we need to handle the response from the server. We do this by setting an event listener for the readystatechange event of the XHR object. This event is fired every time the readyState property of the XHR object changes, which happens several times during the request-response cycle.

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    // Handle the response
  }
};

Inside the event listener, we check the readyState property of the XHR object to see if the request has been completed. If the readyState is XMLHttpRequest.DONE, which is a constant value that represents the request that has been completed, we can handle the response by accessing the responseText property of the XHR object.

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      // Handle the response
      console.log(xhr.responseText);
    } else {
      // Handle the error
      console.log('Error: ' + xhr.status);
    }
  }
};

In the above example, we check the status property of the XHR object to see if the request was successful. If the status is 200, which is a status code that represents a successful request, we can handle the response by accessing the responseText property of the XHR object. The responseText property contains the response from the server as a string.

If the status is not 200, we can handle the error by displaying an error message to the user.

Adding Request Headers

HTTP requests can also include headers, which provide additional information about the request or the client. We can add headers to an XHR object by calling the setRequestHeader() method before calling the send() method.

xhr.setRequestHeader(header, value);

The header parameter is the name of the header, and the value parameter is the value of the header. For example, we can add a Authorization header to include an access token for authentication.

xhr.setRequestHeader('Authorization', 'Bearer token123');

Using Promises

Using the XHR object to make HTTP requests can result in callback hell, a common problem in JavaScript code where multiple nested callbacks can make the code difficult to read and maintain. One way to avoid callback hell is to use Promises.

A Promise is an object that represents a value that may not be available yet but will be resolved in the future. We can use Promises to make HTTP requests by wrapping the XHR object in a Promise.

function http(method, url, headers = {}) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    Object.keys(headers).forEach(function(key) {
      xhr.setRequestHeader(key, headers[key]);
    });
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          resolve(xhr.responseText);
        } else {
          reject(xhr.status);
        }
      }
    };
    xhr.send();
  });
}

In the above example, we define a function called http that takes in a method, url, and headers object as parameters. Inside the function, we create an XHR object, set the request headers, and define the onreadystatechange event listener. We wrap the entire XHR object inside a Promise and call the resolve() function when the request is successful or the reject() function when the request fails.

To use the http function to make an HTTP request, we can call it like this:

http('GET', 'https://jsonplaceholder.typicode.com/posts/1')
  .then(function(response) {
    console.log(response);
  })
  .catch(function(error) {
    console.log('Error: ' + error);
  });

Conclusion

Making HTTP requests is a common task in web development, and JavaScript provides several ways to do it. The XMLHttpRequest object is the most commonly used method, and it provides an easy way to send and receive data from a web server using JavaScript. By understanding how to use the XHR object, add request headers, and handle the response, you can create powerful web applications that communicate with a server. Using Promises can help make your code more readable and maintainable, and it is a good practice to follow.


Thanks for reading. If you like it, then please share this article with others.

Follow for more such technical content.