OneCompiler

Different ways to make an HTTP request

Javascript has many libraries to make an HTTP request. Generally, HTTP requests are used to send or receive data from the client to the server or from the server to the client.

** Ajax**:

Ajax is the old and traditional way to make an asynchronous HTTP request. The POST method is used to send data to the server and the GET method is used to send data to the client. In ajax we need to initialize the xmlHttpRequest() class. Finally, we use the open() method to make an HTTP request.

const Http = new XMLHttpRequest();
const endPoint='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", endPoint);
Http.send();

Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}

Jquery:

Jquery has many methods available to make an HTTP request. Jquery makes very easy for rest calls. We need to include Jquery library in our code to make HTTP calls.


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

** $.ajax**:

.ajax is one of the method available in jquery method.


$.ajax({
     type: "POST",
     url: '/users',
     data: JSON.stringify(result),
     contentType:"application/json",
     dataType:"json",
     complete : function(data){
     console.log('Status: '+ data.status );
     console.log('responseText: '+ data.responseText);
     if(data.status != 200){
         var error_result = JSON.parse(data.responseText);
         alert(error_result);
         return;
     }
     window.location = '/dashboard';
     }
 });

request:

request is another module which comes with npm(node package manager). This request() modules return data using callbacks. Let's look at the example.

const apiUrl = `https://jsonplaceholder.typicode.com/posts`;

request(apiUrl, (error, response, body) => {
      if (error) {
        console.log('error:', error);
        
       } 
       else if (response && response.statusCode == 200) {
        res.send(body);
    }
       });

Axios:

Axios is also another module which is available in NPM(node package manager). Axios uses promises to return data. Promises are available in ES6. It's syntactic sugar of callbacks. Promises are introduced to solve the callback hell issue.

To install Axios we use NPM


npm install axios --save

Lets see an example how can we make HTTP request using Axios

** GET method**:


const apiUrl = `https://jsonplaceholder.typicode.com/posts`;

axios.get(apiUrl)
.then(data => console.log(data))
.catch(err => console.log(err))

** Post method **:

const apiUrl = `https://jsonplaceholder.typicode.com/posts`;

const data = {}

axios({
  method: 'post',
url: apiUrl,
data:{
  data
}
})
.then(data => console.log(data))
.catch(err => console.log(err))