axios入门教程

1、axios是什么

Axios 是一个基于  promise的 HTTP 库,可以用在浏览器和 node.js 中。

2、axios如何安装

(1)使用npm方式进行安装

npm install axios

(2)使用bower方式进行安装

bower install axios

(3)使用cdn方式进行安装

<script src=”https://unpkg.com/axios/dist/axios.min.js”></script>

3、axios使用案例

(1)get请求方式

将请求参数拼接到url中

const axios = require(‘axios’);
 
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
  });
 
 

将请求参数放到params

axios.get(‘/user’, {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

 想要使用异步/等待?在外部函数/方法中添加’async关键字。 

async function getUser() {
  try {
    const response = await axios.get(‘/user?ID=12345’);
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

(2)post请求方式

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

 

执行多个并发请求

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) {
    //2个post请求现已完成
  }));

4、整合vue-axios

(1)安装vue-axios

npm install –save axios vue-axios

(2)在main.js中加入

import Vue from ‘vue’
import axios from ‘axios’
import VueAxios from ‘vue-axios’
 
Vue.use(VueAxios, axios)

(3)vue-axios使用方法

这里以get请求方式举例说明,其它请求方式类似。

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.$http.get(api).then((response) => {
  console.log(response.data)
})

 

0

评论0

请先
显示验证码
没有账号?注册  忘记密码?