DEV Community

Leo Kalshteyn
Leo Kalshteyn

Posted on

Promises and Axios

I stumbled upon a JavaScript library called Axios while looking up alternatives to the fetch API which I used in previous projects. It is promise based like fetch, however, it has some features which fetch doesn't. It is used to make http requests from node.js or XMLHttpRequests from the browser.

Here are some of these features:

  • has a way to abort a request
  • has a way to set a response timeout
  • has built-in CSRF protection
  • supports upload progress
  • performs automatic JSON data transformation
  • has built-in support for download progress.
  • has the ability to cancel requests.

Axios also provides more functions to make other network requests as well, matching the HTTP verbs that you wish to execute:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

Another cool feature is that Axios is able to intercept HTTP requests. Interceptors can be really helpful when we want to examine or change HTTP requests from our application to the server, such as retrieving a token from local storage and including it in all requests.

Axios API
An HTTP request from an axios object looks like:

axios({
  url: 'https://store.ceo/api/products/list/all',
  method: 'get'
})
Enter fullscreen mode Exit fullscreen mode

The promise it returns can contain await to resolve it to the response object.

axios({
;(async () => {
  const response = await axios({
    url: 'https://store.ceo/api/products/list/all',
    method: 'get'
  })
Enter fullscreen mode Exit fullscreen mode

A more elegant way to code this syntax-wise would look like this (Axios methods are very similar to fetch)

;(async () => {
  const response = await axios.get('https://store.ceo/api/products/list/all')
  console.log(response)
})()
Enter fullscreen mode Exit fullscreen mode

Axios has methods for all of for all the HTTP commands such as

It is also important to note that Axios depends on a native ES6 Promise implementation.

References

Top comments (0)