Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 6, 2021 03:32 am GMT

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!


Original Link: https://dev.to/programmingnate/why-axios-is-awesome-and-how-to-get-started-with-it-2ncj

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To