Ways To Make HTTP Request in Javascript
Tags: javascript, programming, api, tutorial
Published: 2022-09-12 05:26:20


Ways To Make HTTP Request in Javascript

It is Very Crucial  To Know How to make HTTP Request to an Endpoint and Being Able to Send or Retrieve or  Get Data. Javascript Has Various Ways  and methods of Making HTTP Request To Various Server Endpoints and Database.
In This Article, we are  Going To Be Discussing the Various Ways to Make HTTP Request In The Javascript Language

**1) XMLHttpRequest**

XMLHttpRequest is A  Built-In Object in Javascript for Making HTTP request From A Web Server. This Was the Only Way and Method Of Making HTTP Request  in The Javascript Language Before ES6.  We Can Receive and Obtain Data Using HTTP GET Method and We Can Send Data Using HTTP POST Method

In This Example We are Going To Be Making Use of JSON Placeholder API which a free api made for developers for testing
**Step 1**
We Create a new instance of  `XMLHttpRequest()` Object

```
//Creating a new instance of XMLHttpRequestObject

const request = new XMLHttpRequest();
```

**Step 2**
We  Proceed to create a new HTTP Request From a Server Endpoint

```

//Creating a new instance an XMLHttpRequest Object
const request = new XMLHttpRequest();
//open the request
request.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
//sending the request 
request.send();

```

We then Open The Request Using  `open() `method which  has Two Parameters which  the first Paremeter is the  HTTP type / method of  request , for this case it  is a GET request we are performing.

While the second parameter is the server endpoint from which we want to get data from. We then Send the request using the `send() `Method

**Step 3**

We have to track the progress of  request to know if the request  is successful or not so we add an eventlistener to the request to listen to the `readystatechange` Event which  is been executed when the readyState property of XMLHttpRequest Changes
readyState with the value of 4 Means The request is complete and status of 200 means the request is successful

```
//Creating a new instance an XMLHttpRequest Object
const request = new XMLHttpRequest();
//open the request
request.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
//sending the request 
request.send();

request.addEventListener('readystatechange', ()=>{
    if(request.readyState == 4 && request.status == 200){
        console.log(request.responseText);
    } else{
        console.log('error in  getting data');
    }
})
```


So, We performed and `if()` statement to check if the readyState is equals to 4 and also if the status is 200 which  means our request was successful so we console.log() request.responsetext which is the text(data) received from the server endpoint in which we made our request and also an else to log error message in the console if the request was nit successful. In This Example our endpoint is the JSON Placeholder API .
In Our Console You Would See something like this .

```
{
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  }
  
```

We have finally and successfully Gotten a Fake id from JSON Placeholder API using XMLHttpRequest

**2) Using The Fetch API**

Fetch API helps us make to make HTTP Request in a similar manner with XMLHttpRequest but Fetch Makes use of the Promise API .When We make a request using fetch API it returns a promise which is asynchronous in nature .
Fetch API Has one mandatory parameter which is the server-side URL

```
//Fetch Api
fetch('https://jsonplaceholder.typicode.com/todos/1')
```


```
//Fetch Api
fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) =>{
   // it returns a promise
  return response.json();
}).then((response) =>{
    console.log(response);
}).catch((err)=>{
     console.log(err);
})
```

We tack on the `then()` method to fetch API which returns our request response and we then log our response to the console. `.catch()` method helps us catch error in our request if there is a error in our HTTP request.
In Our Browser Console we get an output which is an object :

```
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
```


**3) Axois** 

Axois is a library for making HTTP Requests to various endpoints .Axios is a promise based method of making HTTP Request. A Unique feature of axios is that it returns JSON Data already parsed .Axios makes use of XMLHttpRequest Method  under the hood.
Installing Axios
We can make use of axios by installing it ,there are other methods of installing axios but we are going to make use of a CDN in this article
 

```
  //Using CDN
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```

We place this Script tag in the Head  Section of the HTML file

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ways To Make HTTP Request with javascript </title>
    <link rel="stylesheet" href="style.css">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
```

Now we can now proceed to make HTTP Requests using axios

```
//axios
axios.get('https://jsonplaceholder.typicode.com/todos/1').then((data)=>{
   console.log(data);
}).catch((err)=>{
  console.log(err);
})
```


We make a GET Request by calling get Method on axios with URL we want to send a request to  get data From. It returns a promise
In the browser console we have an object  which contains our data :

```
{data: {…}, status: 200, statusText: '', headers: {…}, config: {…}, …}

```


4) **Using JQuery**

jQuery has several methods to make HTTP Requests But for the sake of this tutorial we would be using `$.ajax()` method .
`$.ajax()`  method is used to make  asynchronous HTTP Requests to a specific URL  or Endpoint .
To be able to make use of ` $.ajax()  ` you include its library  source file in the head section of your html page

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

```

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ways To Make HTTP Request with javascript </title>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

```
Below is the syntax of $.ajax()

```
$.ajax({
  url: url,
  type: type,
  success: success,
  error : error
});

```
**url:** it is the  URL / endpoint with which we	 want make a request to using ajax.

**type:**  it defines the type of HTTP Method in the request

**success:** it is a  callback function fired based on response of the request if it is successful

**error:** it is a  callback function fired based on response of the request if there is an error in the request 




```
$.ajax({
  url: 'https://jsonplaceholder.typicode.com/todos/1',
  type: 'GET',
  success: (res) =>{
     console.log(res);
  },
  error : (err) =>{
    console.log(err);
  },
});

```


In the browser console you get response of the request which is shown below:

```
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
```
Conclusion

We have learnt various ways to make HTTP Request in javascript . You can use any of the various methods to make request in your projects.Happy Coding !!