Javascript

Making Http Requests in Javascript Using Axios

javascript making http requests using axios

Making http requests or ajax calls is an important aspect in modern web applications which fully rely on Javascript, in this post we will cover how to make http requests using Javascript library called axios.

 

 

Axios is a promise based javascript library for making ajax requests used in modern frontend frameworks. In contrast with the native XMLHttpRequests object and jquery ajax() function, axios support all features when making http calls so there are methods for handling “GET, POST, DELETE, PUT, PATCH” and more. Axios also has a great support for sending headers and csrf tokens.

Beside that axios is based on Ecmascript 6 Promise Api so methods such as “then” and “catch” are available in it’s core. Axios also has a great support in all the major browsers.

 

To read more about the Promise Api refer to this article.

 

Can i use axios beside jquery?

Yes, you can use axios with any library and it does not conflict when used with jquery as it’s not dependent on any other library.

 

Installing

You can use a direct cdn:

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

Or if you intend to with npm you can install it easily using this command:

npm install axios

Most frontend frameworks like ReactJs and Vuejs makes use of axios when dealing with ajax requests.

 

Examples

  • Making a GET request
axios.get('https://jsonplaceholder.typicode.com/todos')
  .then(function (response) {       
    // on success
    console.log(response);
  })
  .catch(function (error) {   
    // on error      
    console.log(error);
  });

When running the above script you will see that it has a response similar to this:

javascript axios sample response

The “data” property on the response object is the actual data you looking for. So to get the data call response.data in the above example like this:

....
then(function(response) {  
    console.log(response.data); 
})
....

The “headers” property contains the headers returned from the server. The “status” and “statusText” properties specify the status of the response, you can use this to check for example is the response is successful or not.

 

  • Making a GET request with parameters

The first method is to pass parameters along with the url like this:

...
xios.get('https://jsonplaceholder.typicode.com/todos/1')
        .then(function(response) {  
           console.log(response.data); 
});
...

Or you can pass an object as the second parameter to axios.get():

...
axios.get('https://jsonplaceholder.typicode.com/todos', {params: {id: 1}})
         .then(function(response) {  
             console.log(response.data); 
})
...

 

  • Making a POST request
axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'new title',
    body: 'new body'
  })
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

As you see i passed the post params as the second parameter to axios.post().

  • Making a PUT and PATCH request
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
    title: 'updated title',
    body: 'updated body'
  })
  .then(function (response) {
    console.log(response.data);
  });
axios.patch('https://jsonplaceholder.typicode.com/posts/1', {
    title: 'updated title 2',
    body: 'updated body 2'
  })
  .then(function (response) {
    console.log(response.data);
  });

As you see above i sent the id of the resource being updated appended to the url.

 

  • Making a DELETE request
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
  .then(function (response) {
    console.log("post deleted");
  });

 

Other syntax for axios

Axios supports other syntax for making http requests similar to jquery.ajax() function:

axios(config)
axios(url[, config])
axios({
  method: 'post',
  url: 'https://jsonplaceholder.typicode.com/posts',
  data: {
    title: 'new title',
    body: 'new body'
  }
});
axios({
  method: 'get',
  url: 'https://jsonplaceholder.typicode.com/posts/20',
  responseType: 'json'
})
  .then(function (response) {
    console.log(response.data);
  });

As shown above you can send a config object to axios specifying the method, url and optional parameters.

Making multiple requests with axios

As we described axios above we said that it’s based on Promise Api so we can make use to functions like Promise.all() this methods used to execute multiple concurrent promises, like in this example:

function getTodos() {
  return axios.get('https://jsonplaceholder.typicode.com/todos');
}

function getPosts() {
  return axios.get('https://jsonplaceholder.typicode.com/posts');
}

axios.all([getTodos(), getPosts()])
  .then(axios.spread(function (todos, posts) {
    console.log(todos, posts);
  }));

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments