axios

今天在做一个关于vue的后端管理系统时,遇到了axios语法糖async和await的用法,以及axios请求拦截器的使用。由于对这两个方面不太熟悉,所以想对axios的使用做一下总结。

什么是axios ?

Axios 是一个基于 promise 的 HTTP 库,它专注于网路数据请求。

axios的使用

axios支持各种数据请求方式,在这里只以get和post为例。

发送get请求:
// 第一种携带数据的方式,使用查询字符串的方式,这也是get请求携带参数的方式
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });
// 第二种携带数据的方式
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  • .then回调函数是处理请求发送成功后的响应结果。调用 axios 方法得到的返回值是 Promise 对象。response中的数据不是接口返回的真实数据,response.data才是真实数据

  • .catch回调函数捕捉请求发送失败的接结果

发送post请求:
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios发送请求:
//发送post请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// 发送get请求
axios({
  method: 'get',
  url: '/user',
  params: {
    id: 123456
  }
})
// 若不写methods默认是get请求
async/await:

在ECMAScript 2017中提供了axios的语法糖,可以简化axios发送请求。async写在函数前,await写在该函数中的axios请求前。

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
    }
}
  
执行多个并发请求:
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });
全局的 axios 默认值
axios.defaults.baseURL = 'https://api.example.com';
拦截器
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

// 移除拦截器
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值