tiny-axios-wrap

0.1.6 • Public • Published
npm install --save tiny-axios-wrap

Use

// import tiny-axios
import ajax from 'tiny-axios-wrap'
 
ajax(config, options)
.then(res => {
  // 若 code == 0, 为有效返回,则 res 返回的都是有效数据
  // res => {
  //  config: {},  请求的配置
  //  data: { code: 0, data: '' },  返回的数据
  //  ...
  // }
})
.catch(err => {
  // 请求错误、code != 0,都在这里返回
})
 
/**-------------config--------------------------**/
config = {
  method: 'post',
  url: '',
  data: {}
}
config = {
  method: 'get',
  url: '',
  params: {}
}
 
// 设置超时,10秒
config.timeout = 10000;
 
// 设置 json 格式请求
config = {
  headers: {
    'Content-Type': 'application/json'
  },
  transformRequest: [function (data) {
    return JSON.stringify(data);
  }]
}
 
/**------------options---------------------------**/
options = {
  // loading组件,加载状态,不需要自动关闭
  loading: {
    open() {},
    close() {}
  },
  // toast组件,错误弹框,应能自动关闭
  toast: {
    open() {},
    success() {},
    error() {},
    warn() {}
  },
  // 允许正常输出的,非成功返回码, number
  outputCodes: [],
  // 根据返回码拦截处理
  resCodeIntercept: [
    { code: '', handler() {} }
  ],
  utils: {
    auth: {
     // 特征码字段
     code: 'code',
     // 成功代号
     num: 0,
     // 失败提示字段
     message: 'error',
      defaultReqErrorBefore: 'rq',
      defaultResErrorBefore: 'rs',
      defaultReqErrorCode: '000',
      defaultResErrorCode: '000',
    },
    alert: {
       /* timeout 连接超时*/
     timeoutError: '连接超时,请重试',
      // 没有数据返回
      notFoundData: '没有数据',
     otherError: '网络错误'
    }
  }
}

// 简单的自定义封装
import axios from 'tiny-axios-wrap'
import Loading from 'tiny-loading'
import Tost from 'tiny-tost'
let ajax = (config) => {
  let options = {
    loading: Loading,
    toast: Tost,
    resCodeIntercept: {
      code: 202,
      handler() {
        console.log(202)
      }
    },
    utils: {
      auth: {
       code: 'code',
       num: 0,
       message: 'msg'
      }
    }
  }
  return new Promise((resolve, reject) => {
    axios(config, options)
    .then(res => {
      res.data.code === 0 && resolve(res.data)
    })
    .catch(err => reject(err))
  })
}
ajax.prototype.then = res => {}
ajax.prototype.catch = err => {}
 
export default ajax
 
// 使用
ajax({
  method: 'post',
  url: 'http://xxxxxx',
  data: {}
})
.then(res => {
  console.warn(res);
})
.catch(err => {
  console.error(err);
})

/tiny-axios-wrap/

    Package Sidebar

    Install

    npm i tiny-axios-wrap

    Weekly Downloads

    7

    Version

    0.1.6

    License

    MIT

    Last publish

    Collaborators

    • dengchao2056