DEV Community

Nathan Sheets
Nathan Sheets

Posted on

Why Axios Is Awesome (and how to get started with it)

Making HTTP requests can easily get bloated and unnecessarily complex. Sure, you can use jQuery's ajax methods or even jquery.get, but that has its limitations and doesn't fit well with a code base that's heavily based on promises.

Enter: Axios. Axios is a promise-based HTTP handler that makes your life a thousand times easier. It's very simple to use. For example, an ajax request through jQuery could take up a dozen lines or more, and the more lines of code that aren't abstracted away from you, the more room for error and bugs.

An axios request can take two primary forms for most uses. The simplest one, for example, a GET request, looks like this:

const axios = require('axios');
axios.get('YourURLorEndpointHere');
Enter fullscreen mode Exit fullscreen mode

That's a simple get request. The fun part is that that statement on the second line actually returns a promise, so you could handle the response extremely easily. For example:

const axios = require('axios');
axios.get('YourURLorEndpointHere')
  .then(response => {
    //do something
  })
  .catch(err => {
    //do something else 
  });
Enter fullscreen mode Exit fullscreen mode

And you're done. That's it. That's the whole get request, handled and caught.

Let's say you wanted to make a post request instead, and you wanted to add some options in there. You can also use Axios as a function and give it an object with what ever parameters you want. For example:

axios({
  method: 'post',
  url: 'yourURLorEndpointHere',
  data: {
    //Your info to send here
  }
})
.then(response => {
  //do something with the response
})
.catch(err => {
  //handle any errors
});
Enter fullscreen mode Exit fullscreen mode

That's it. That's what you'd use in 90% of any situations you'll run across, at least for simpler websites. Axios can help you make simpler, easier, and cleaner HTTP requests.

Bonus: If you don't already use it, Express is a great tool for receiving all those super clean requests you just made!

Top comments (4)

Collapse
 
epsi profile image
E.R. Nurwijayadi

You can utilize fetch from WHATWG, and combine with async from ES 2107.

🕷 epsi-rns.gitlab.io/code/2020/10/25...

ES - Fetch Async/Await

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Also,

const data = await fetch(url).then(r => r.json())
Enter fullscreen mode Exit fullscreen mode

if you don't need to catch response.ok (i.e. statusCode >= 200 && statusCode < 300).

Collapse
 
qm3ster profile image
Mihail Malo

It's nice, maybe for prototyping, but just writing a small wrapper around fetch is all it takes these days to implement even the most complicated interceptor logic. And if you need to support old browsers, you just polyfill fetch (only in legacy bundle).

Collapse
 
isvander profile image
Isvander

might be the best way for someone who hate to use jquery?