JavaScript - HTTP Requests


Http is a protocol, stands for hypertext transfer protocol. The http requests are used to communicate with web servers. It allow us to send requests to a server and get responses. These can be used to fetch data, submit forms, upload file and more.

HTTP Methods

These are the most commonly used HTTP methods:

  • GET:This method is used to get information from a server that we need. We can think of it like asking for a piece of information without sending anything extra to server.
  • POST:This method is used to send data to a server which stores that data. Usually when submitting a form, we store information onto the server.
  • PUT: This is method is used for updating the data which is already available onto the server. For example, in the code Snippet, you filled the form with incorrect information and have to make it correct.
  • DELETE: This method is used to delete something that you don't need anymore, you can delete that from server.
  • PATCH: This method helps while updating partial information. In the code snippet, if you made typos in forms, you can update them with PATCH.

Ways to Make HTTP Requests in JavaScript

There are ways to make http requests in javascript those are below:

  • Using XMLHttpRequest (XHR)
  • Using Fetch API

Using XMLHttpRequest (XHR)

XMLHttpRequest is an old built-in browser object that help us to make http requests in javascript. It is used to get data from the server and send data to the server.

Code Snippet

Below code snippet shows you how we can make request using XMLHttpRequest


// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure it: GET-request for the URL /article/.../load
xhr.open('GET', '/article/.../load', true);

// Send the request over the network
xhr.send();

This is how we can make a very simple GET request using XMLHttpRequest. We can also make POST, PUT, DELETE requests using the same XMLHttpRequest.

Using Fetch API

The Fetch API is a new modern way to make a http requests in JavaScript. It helps us to grab data from the server, and send data to the server. It is built-in the browsers, which means that you would not need any extra libraries to use it.

Code Snippet

Below code snippet shows you how we can make request using Fetch API

// Make a request
fetch('/article/.../load')
  .then(response => response.json())
  .then(data => alert(data.title))
  .catch(error => alert(error));

This is how we can make a simple and easy GET request using Fetch API. We can also make POST, PUT, DELETE requests using Fetch API as well.

Conclusion

HTTP requests are mostly used to communicate with web servers. We do have several methods to make request. We can use these requests to fetch data, submit forms, upload files and many more. There are two ways to make http requests in javascript, those are using XMLHttpRequest and Fetch API.

Advertisements