Basic use of Axios

Time:2020-9-22

Axios basic usage Axios is a promise based HTTP library that can be used in browsers and node.js Medium. It is recommended to use Axios to implement Ajax in Vue.

A simple get example
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://www.runoob.com/try/ajax/json_demo.json')
      .then(response => (this.info = response.data.sites))
      . catch (function (error) {// request failure processing
        console.log(error);
      });
  }
})

The two methods of transmitting parameters are as follows

//Add parameter id = 12345 directly to the URL
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
 
//Parameters can also be set through params:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
For post method
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .post('https://www.runoob.com/try/ajax/demo_axios_post.php')
      .then(response => (this.info = response))
      . catch (function (error) {// request failure processing
        console.log(error);
      });
  }
})

Post transmission

axios.post('/user', {
    Firstname: 'Fred', // parameter firstname
    LastName: 'Flintstone' // parameter LastName
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
For multiple concurrent requests
function getUserAccount() {
  return axios.get('/user/12345');
}
 
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    //Both requests are now executed
  }));
The Axios API can create requests by passing configuration to Axios.
axios(config)
//Send post request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
//Get request remote picture
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
axios(url[, config])
//Send get request (default method)
axios('/user/12345');
Alias of the request method

To facilitate use, the official authorities provide aliases for all supported request methods. You can directly use the alias to initiate requests

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Helper function for concurrent processing of concurrent requests:
axios.all(iterable)
axios.spread(callback)