Skip to content
Home » Blog » How to use HTTP requests in JavaScript

How to use HTTP requests in JavaScript

HTTP requests in JavaScript are a crucial aspect of modern web development. These requests are used to fetch data from servers and APIs, and to send data to those same servers and APIs. JavaScript provides a number of built-in methods for making HTTP requests, which can be used to build robust and responsive web applications. In this blog post, we will explore HTTP requests in JavaScript and discuss how to use them effectively.

What is an HTTP request?

HTTP (Hypertext Transfer Protocol) is a protocol used to transfer data over the internet. Requests made by a client (such as a web browser) to a server for a specific resource (such as a webpage or an image). HTTP requests have several components, including the URL of the resource being requested, the HTTP method being used (such as GET or POST), and any data or parameters that need to be sent with the request.

Types of HTTP requests

There are several types of HTTP requests, but the most commonly used ones are:

  1. GET – used to retrieve data from a server
  2. POST – used to send data to a server
  3. PUT – used to update data on a server
  4. DELETE – used to delete data from a server

Making an HTTP request in JavaScript

To make an HTTP request in JavaScript, we need to use an XMLHttpRequest object. The XMLHttpRequest object is a built-in object in JavaScript that provides a way to make HTTP requests to a server.

To make an HTTP request using XMLHttpRequest, we first need to create a new instance of the object:

let xhr = new XMLHttpRequest();

Once we have created the XMLHttpRequest object, we can use its methods to make a request. The most commonly used methods are:

  1. open() – opens the connection to the server
  2. send() – sends the request to the server
  3. onload() – handles the response from the server

Here is an example of making a GET request using XMLHttpRequest:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Request failed. Status code: ' + xhr.status);
  }
};
xhr.send();

In this example, we create a new instance of XMLHttpRequest and use the open() method to specify that we want to make a GET request to the URL https://jsonplaceholder.typicode.com/todos/1. We then use the onload() method to handle the response from the server. If the request is successful (i.e. the status code is 200), we log the response text to the console. If the request fails, we log an error message with the status code.

Making a POST request in JavaScript

To make a POST request in JavaScript, we need to use XMLHttpRequest as well. The only difference is that we need to pass the data we want to send as an argument to the send() method.

Here is an example of making a POST request using XMLHttpRequest:

let xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = function() {
  if (xhr.status === 201) {
    console.log(xhr.responseText);
  } else {
    console.log('Request failed. Status code: ' + xhr.status);
  }
};
let data = JSON.stringify({
  title: 'foo',
  body: 'bar',
  userId: 1
});
xhr.send(data);

In this example, we create a new instance of XMLHttpRequest and use the open() method to specify that.

Handling errors and exceptions

When making HTTP requests in JavaScript, it’s important to handle errors and exceptions. For example, if the server is down or the network connection is lost, the request may fail. To handle these situations, we can use the onerror() method of the XMLHttpRequest object.

Here is an example of handling errors in XMLHttpRequest:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.log('Request failed. Status code: ' + xhr.status);
  }
};
xhr.onerror = function() {
  console.log('Request failed. Network error.');
};
xhr.send();

In this example, we use the onerror() method to handle any network errors that may occur. If the request fails due to a network error, we log an error message to the console.

Using Fetch API

In addition to XMLHttpRequest, JavaScript also provides the Fetch API for making HTTP requests. The Fetch API provides a simpler and more flexible interface for making HTTP requests, and is gradually becoming the preferred method for making HTTP requests in modern web development.

Here is an example of making a GET request using Fetch API

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Conclusion

HTTP requests are an essential part of modern web development, and JavaScript provides a number of built-in methods for making these requests. By using XMLHttpRequest or Fetch API, we can fetch data from servers and APIs, and send data to those same servers and APIs. With proper error handling, we can build robust and responsive web applications that provide a seamless user experience.

For more JavaScript blog(s) visit: https://geekalgo.com/category/js/

Leave a Reply

Your email address will not be published. Required fields are marked *