@shitou/tea-plus

ajax promise

Usage no npm install needed!

<script type="module">
  import shitouTeaPlus from 'https://cdn.skypack.dev/@shitou/tea-plus';
</script>

README

teaPlus 使用文档

安装

npm i @shitou/tea-plus --save-dev

使用

引用

import teaPlus from '@shitou/tea-plus'

使用api

  • GET方式
teaPlus
    .get(URL,config)
    .then(res => {
             console.log(res)
    })
    .catch(e => {
                console.log(e)
    })

teaPlus
    .delete(URL,config)

teaPlus
    .head(URL,config)

teaPlus
    .options(URL,config)

  • PLOS方式
teaPlus
    .post(URL,config)
    .then(res => {
             console.log(res)
    })
    .catch(e => {
                console.log(e)
    })

teaPlus
    .put(URL,config)

teaPlus
    .patch(URL,config)

Config配置参数

参数名字 类型 默认值 参数描述
params Object null 只给get方式请求传递参数试用可以不传
data Object null 只给post方式请求传递参数试用可以不传
timeout Number 0 接口超时时间配置,以毫秒(ms)为单位
withCredentials Boolean False 是否开启ajax跨域请求
headers Object {} 配置请求头文件
cache Boolean true 为false时自动在请求链接后面加入时间戳凡防止缓存
mark Boolean false 为true时会自动配合 mark 打点 计算接口响应时间

返回参数详解

参数 类型 默认值 参数描述
res Object null 请求成功返回参数
res.data Object null 接口返回的内容
res.status Number null 接口返回的状态码
res.statusText String 空字符串 接口返回的与状态码相对应的状态消息
res.headers Object null 接口返回的的头信息
res.config Object Object 用户的config配置信息
res.request Object Object XMLHttpRequest 对象

错误参数详解

参数 类型 默认 参数描述
e String 空字符串 错误信息内容
e.message String 空字符串 错误信息内容
e.config Object Object 用户的config配置信息
e.code Number null 接口返回的状态码
e.request Object null XMLHttpRequest 对象
e.response Object null XMLHttpRequest 对象
e.isTeaPlusError Boolean false 是否是 timeout 网络异常 返回码不正常的 teaPlus内部错误的情况判断

其他使用方法

  • teaPlus.all:等同于promise.all

  • teaPlus.create:创建静态类

  • teaPlus.spread:等同于promise.spread分别获取 promise.all的结果

拦截器

// 添加一个请求拦截器
teaPlus
    .interceptors
    .request
    .use(function (config) {
      
        // 在发送请求之前可以做一些事情
        return config;
    }, function (error) {
        console.log(error)
        // 处理请求错误
        return Promise.reject(error);
    });

// 添加一个响应拦截器
teaPlus
    .interceptors
    .response
    .use(function (response) {
        console.log(222)
        // 处理响应数据
        return response;
    }, function (error) {
        // 处理响应错误
        return Promise.reject(error);
    });

兼容处理

因为低版本的浏览器不支持promise,本库的链式调用是基于原生promise,本库推荐使用es6-promise所兼容

安装地址:https://www.npmjs.com/package/es6-promise

可以用
require('es6-promise').polyfill();
或者
require('es6-promise/auto');
 

或者引用

<!-- Automatically provides/replaces `Promise` if missing or broken. -->
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script> 
 
<!-- Minified version of `es6-promise-auto` below. -->
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>