基于axios封装的api请求函数

       在vue2.0不推荐使用vue-resource之后,大部分人的选择基本上都是axios,axios不光在vue上用,在angular和react上也能用。所以学会用它总会有用的。

      如果你属于还不知道怎么用的话,先看一下这篇文章:https://www.kancloud.cn/yunye/axios/234845

     如果每次发起请求都完完整整的写一遍的话就会是这个样子:

axios.get('/user?ID=12345')

  .then(function (response) {

    if (response.data.code === 200) {

        //请求成功执行

    } else {

        // 错误执行语句

    }

  }).catch(function (error) {

       // 由网络或者服务器抛出的错误

     alert(error.toString())

  })

嗯  看起来不是很复杂,但是这段代码固定了axios的的config配置,包括方法,路径,header【content-type】等等。这些在同一个项目里面都是需要不停更改的。因此,我们写一个函数能够最简单的方便我们快速发起请求。


export function fetch(method, url, params, type, contentType) {
  if (type == 'json') {
    typeHttp = type;
  } else {
    typeHttp = ''
  }
  return new Promise((resolve, reject) => {
    switch (method) {
      case 'post':
        if (contentType === 'json') {
          axios.post(url, params, {
            headers: {
              'Content-Type': 'application/json',
            }
          })
            .then(response => {
              typeHttp = '';
              resolve(response.data);
            }, err => {
              typeHttp = '';
              reject(err);
            })
            .catch((error) => {
              typeHttp = '';
              reject(error)
            })
        } else {
          axios.post(url, params,)
            .then(response => {             
              typeHttp = '';
              resolve(response.data);

            }, err => {
              typeHttp = '';
              reject(err);
            })
            .catch((error) => {
              typeHttp = '';
              reject(error)
            })
        }
        break;
      case 'get':
        axios.get(url)
          .then(response => {
            typeHttp = '';
            resolve(response.data);
          }, err => {
            typeHttp = '';
            reject(err);
          })
          .catch((error) => {
            typeHttp = '';
            reject(error)
          })
        break;
      default:
        Message.error('method出错!');
        break;
    }
  })
}

代码如上面,利用promiss异步函数,我们调用函数后使用.then()执行回调。

例子:

 //调用fetch函数
getTbCount(params) {
    return fetch('post', '/web/url', params);
  },


//外部引用api,并处理数据(优势是可以把所有api放在一个文件里,方便维护)
api.getTbCount(params)
.then(res => {
   if (res.code && res.code == '200') {
      if (res.data) {
              //成功回调
       }
    }  else {
              _.message('error',res.message);
              return false;
     }
})
.catch(err => {console.log(err, '0')});

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值