javascript making http requests using axios

Making Http Requests in Javascript 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:

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

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

 

Examples

  • Making a GET request

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:

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:

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

 

  • Making a POST request

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

  • Making a PUT and PATCH request

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

 

  • Making a DELETE request

 

Other syntax for axios

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

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:

 

Share this: