Vuejs sending HTTP/Ajax request with axios

Vuejs sending HTTP/Ajax request with axios

Mar 18, 2019 / Ramesh Mhetre

axios is one of the most famous JS package available on github. It is a promise based HTTP client for javascript. It can used both on frontend or backend(node.js).

Features of axios:

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

axios examples

Example to make http get request with javascript:

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Example to make http post request with javascript:

 axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios available methods

For convenience aliases have been provided for all supported request methods.

  • 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]])

axios dealing with errors

There are times when we might not get the data we need from the API. There are several reasons that our axios call might fail, including but not limited to:

  • The API is down.
  • The request was made incorrectly.
  • The API isn’t giving us the information in the format that we anticipated.

When making this request, we should be checking for just such circumstances, and giving ourselves information in every case so we know how to handle the problem. In an axios call, we’ll do so by using catch.

axios
 .get('https://xyz.com/api')
 .then(response => (this.info = response.data.bpi))
 .catch(error => console.log(error))

Vuejs axios example

Here is the example how axios can be used in your vuejs component. It has considered that axios has already installed & added.

new Vue({
 el: '#app',
 data () {
  return {
   info: null
  }
 },
 mounted () {
  axios
   .get('https://api.coindesk.com/v1/bpi/currentprice.json')
   .then(response => (this.info = response))
 }
})

Reference link



Similar Articles

VueJs content loading placeholders

VueJs content loading placeholders

Vue Content Loading is a component to use placeholder or preset.
Read more...
Compiling assets with Laravel Mix

Compiling assets with Laravel Mix

Laravel Mix provides a fluent API for defining Webpack build steps
Read more...