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');
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
});
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
});
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)
You can utilize
fetch
fromWHATWG
, and combine withasync
fromES 2107
.🕷 epsi-rns.gitlab.io/code/2020/10/25...
Also,
if you don't need to catch
response.ok
(i.e.statusCode >= 200 && statusCode < 300
).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).
might be the best way for someone who hate to use jquery?