Programmingempire
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.
<script>
const r =new XMLHttpRequest();
r.addEventListener('readystatechange', ()=>{
console.log(r, r.readyState);
if(r.readyState === 4){
document.write(r.responseText);
}
});
r.open('GET', 'https://cataas.com/api/cats?tags=cute');
r.send();
</script>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
Understanding HTTP Requests and Responses
What is Asynchronous JavaScript?
JavaScript Code for Event Handling
Callback Functions in JavaScript
Show or Hide TextBox when Selection Changed in JavaScript
Changing Style of HTML Elements using getElementsByClassName() Method