Understanding HTTP Requests and Responses

This article explains HTTP Requests and Responses. In order to get data from another server HTTP Requests are made. Basically, these requests occur between API endpoints.

API End Points

Generally, two servers interact with each other using web services. So, one of the servers is making a request for a resource. While the other one has the resource at a particular location. These are called endpoints. In other words, the URL at which the request is made and the URL at which the resource resides is called the endpoints. Whenever an HTTP request is made, it is done using API endpoints. In particular, API endpoints represent the base URL where the authentication credentials can be used while making HTTP requests.

HTTP Requests and Responses using JavaScript

At first, we create a request object. Of course, we need a built-in class for that and the XMLHttpRequest class serves this purpose. The following code shows how to create a request object.

const r =new XMLHttpRequest();

Afterward, we can send the request using this object. For this purpose, first, we call the open() method using the request object. This function takes two parameters. The first one is the method ‘GET’ or ‘POST’.While the second parameter indicates where we want to send the request. Specifically, it is the API endpoint. Further, the send() method actually sends the request. Even, we can track the status of our request using the property readystatechange.

As can be seen in the output of console.log(), there are various response codes. So, we can find out if any error occurs by just looking at the response code.

const r =new XMLHttpRequest();
r.addEventListener('readystatechange', ()=>{
	console.log(r, r.readyState);
        if(r.readyState === 4){
});'GET', '');


Example of HTTP Requests and Responses in JavaScript
Example of HTTP Requests and Responses in JavaScript

Related Topics

Evolution of JavaScript from ES1 to ES2020

Understanding Document Object Model (DOM) in JavaScript

Introduction to Programming in TypeScript

Creating Classes in TypeScript

Working with Arrays in TypeScript

Significance of Tuples in TypeScript

Explaining Interfaces in TypeScript with Examples

How to Create and Use Arrow Functions in TypeScript

Understanding JSON Web Tokens

Java Practice Exercise

Introduction to HTML DOM Methods in JavaScript

Changing Style of HTML Elements using getElementsByClassName() Method

Show or Hide TextBox when Selection Changed in JavaScript

JavaScript Code Examples

Callback Functions in JavaScript

JavaScript Code for Event Handling

What is Asynchronous JavaScript?

Leave a Reply

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