@gravityjs/wxaxios

基于Promise封装的wx.request请求的http客户端

Usage no npm install needed!

<script type="module">
  import gravityjsWxaxios from 'https://cdn.skypack.dev/@gravityjs/wxaxios';
</script>

README

wxaxios

An Axios-API like Request Package for MiniProgram

wxaxios 接口请求

针对 wx.request 接口进行二次封装。

  • 使用promise调用风格
  • 加入拦截器功能
  • api方法与axios一致
  • 解除并发请求限制为10
  • cookie处理

使用方式

直接npm安装

npm install @gravityjs/wxaxios -S

然后使用微信开发者工具的构建npm功能

或者直接从@gravityjs/wxaxios包的dist文件中中复制相关类型的js文件放入自己的小程序项目中

目前编译的导出文件有四种:

  • wxaxios.common.js
  • wxaxios.common.min.js
  • wxaxios.esm.js
  • wxaxios.esm..min.js

API

  1. wxaxios(config)

    wxaxios({
        url: 'http://localhost/api',
        method: 'post',
        data: {
            test: '1'
        }
    }).then(function (response) {
        console.log(response);
    });
    
  2. wxaxios(url[, config])

    wxaxios(
        'http://localhost/api',
        {
            method: 'post',
            data: {
                test: '1'
            }
        }
    ).then(function (response) {
        console.log(response);
    });
    
  3. 请求 别名

    1. wxaxios.request(config)
    2. wxaxios.get(url, data[, config])
    3. wxaxios.post(url, data[, config])
    4. wxaxios.delete(url, data[, config])
    5. wxaxios.head(url, data[, config])
    6. wxaxios.put(url, data[, config])
  4. wxaxios.create([defaultConfig])

    通过 wxaxios.create([defaultConfig]) 创建一个全新的 wxios实例。

    var instance = wxaxios.create({
        baseURL: 'http://localhost'
    });
    

    新实例拥有 wxaxios 下挂载的所有request方法。

  5. 请求拦截器

    request拦截器 : wxaxios.interceptors.request

    // 添加一个拦截器
    // 同时返回一个 拦截器标识
    var interceptorId = wxaxios.interceptors.request.use(function(config) {
        // do something...
        // TODO:
        // 每个拦截器都必须返回 config
        return config;
    });
    // 删除一个拦截器
    wxaxios.interceptors.request.eject(interceptorId);
    

    response拦截器 : wxaxios.interceptors.response

    // 添加一个拦截器
    // 同时返回一个 拦截器标识
    var interceptorId = wxaxios.interceptors.response.use(function(response) {
        // do something...
        // TODO:
        // 每个拦截器都必须返回 response
        return response;
    });
    // 删除一个拦截器
    wxaxios.interceptors.response.eject(interceptorId);
    
  6. Default Config

    {
        // 公共接口前缀
        baseURL: '',
        // 公共 headers 配置
        headers: {},
        // 接口超时时间, 单位 ms, 默认为 0,不做超时处理
        timeout: 0
    }
    
    wxaxios.defaults.baseURL = 'http://localhost';
    wxaxios.defaults.headers.common['content-type'] = 'application/json';
    wxaxios.default.headers.post['content-type'] = 'application/json';
    
  7. Concurrency

    {
      concurrency: 10
    }
    

    支持突破小程序wx.request最大并发限制是 10 个

  8. Cookie

    {
      getCookie: () => {}
    }
    

    可以在配置中放入getCookie函数, 方便发送请求时将存入缓存的数据放入Cookie头字段发出

借鉴项目