1.0.7 • Published 11 months ago

weapp-axios v1.0.7

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

Weapp Axios

🌞 用于微信小程序发起 HTTPS 网络请求

Weapp Axios 参考了 Axios,对 wx.request 等网络请求接口进行了进一步的封装

代码片段

更多微信小程序开发工具,查看 微信小程序开发全家桶

安装

npm i weapp-axios

注意:在小程序中使用npm包前,需先构建 npm

使用

发起 wx.request 请求(默认为GET请求)

import axios from 'weapp-axios'

axios('/user/12345')
// 或者
axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred' } })

// 使用别名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

config 配置如下:

{
  //创建请求时使用的方法
  method: 'get',
  // baseURL 将自动加在 url 前面,除非 `url` 是一个绝对 URL
  baseURL: 'https://www.abc.com',
  // url 用于请求的服务器 URL
  url: '/user',
  // 与请求一起发送的 URL 参数
  params: {
    id: 1
  },
  // 作为请求主体被发送的数据
  // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
  data: {
    name: '小明'
  },
  // auth 表示应该使用 HTTP 基础验证,并提供凭据
  // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
  auth: {
    username: 'admin',
    password: '000000'
  },
  // responseType 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default
  // 使用单例模式进行实例化
  // 在单例模式下,类仅有一个实例,实例化时传入的参数也只会在第一次生效
  useSingleton: true,
  // 超时时间
  timeout: 0,
  // 即将被发送的自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  // 响应数据强制转化为json格式
  forcedJSONParsing: true,
  // 本地打印
  openLocalPrinter: true,
  // 本地日志
  openLocalLogger: true
}

发起 wx.uploadFile 请求

import axios from 'weapp-axios'

// 传入 name 以及 filePath 参数会自动发起 wx.uploadFile 请求
axios({ url: 'www.abc.com', name: 'name', filePath: 'filePath' })

// 使用别名
axios.uploadFile('www.abc.com', 'filePath', 'name', {...config})
axios.uploadFile({ url: 'www.abc.com', filePath: 'filePath', name: 'name', ...config })

发起 wx.downloadFile 请求

import axios from 'weapp-axios'

// 传入 filePath 参数会自动发起 wx.downloadFile 请求(wx.downloadFile中的 filePath 为非必填项,可传入空值)
axios({ url: 'www.abc.com', filePath: '' })

// 使用别名
axios.downloadFile('www.abc.com', 'filePath', {...config})
axios.downloadFile({ url: 'www.abc.com', filePath: 'filePath', ...config })

发起 wx.connectSocket 请求

import axios from 'weapp-axios'

axios.connectSocket('www.abc.com', {...config})
// 或者
axios.connectSocket({ url: 'www.abc.com', ...config })

// 实例
const axiosInstance = axios.create({ baseURL: '' })
axiosInstance.connectSocket({
  task: {
    onOpen: (res, task) => {
      // onOpen(res, task)
      wx.showToast({
        icon: 'success',
        title: '连接成功',
      })
    },
    onMessage: res => {
      // onMessage(res)
    },

    onClose: res => {
      // onClose(res)
    },

    onError: res => {
      // onError(res)
    },

    send: task => {
      send(task)
    },

    close: task => {
      close(task)
    },
  },
})
function send(task) {
  // task.send({})
}
function close(res) {
  // task.close({})
}

拦截请求和响应

import axios from 'weapp-axios'

axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  console.log('请求被拦截了')
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
})
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  console.log('响应被拦截了')
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
})

处理 Task 任务对象

wx.request\wx.uploadFile\wx.downloadFile\wx.connectSocket 拥有相同的处理方法。

在 config 内传入合法Task方法的 task 对象。

RequestTask

import axios from 'weapp-axios'

axios.downloadFile({
  url: 'www.abc.com',
  task: {
    // task对象键值命名必须与官方文档Task提供的函数名一致
    onProgressUpdate: (res, task) => {
      // 使用自定义函数接收参数
      yourOnProgressUpdateFun(res, task)
    },
    offProgressUpdate: (res, task) => {
      yourOffProgressUpdateFunc(res, task)
    },
    // 如果不是on监听事件的回调函数,axios传入的是task对象
    abort: task => {
      yourAbortFunc(task)
    },
  },
});

function yourAbortFunc(task) {
  if (true) {
    task.abort()
  }
}

最佳实践

在项目中使用 weapp-axios

// request.ts
import axios from 'weapp-axios'

const service = axios.create({ baseURL: 'https://www.a.com' })

// 请求拦截器
service.interceptors.request.use((config: any) => {
  const token = getToken()

  if (token) {
    config.header['Authorization'] = 'Bearer ' + token
  }

  wx.showLoading({
    title: '加载中',
    mask: true
  })

  return config
}, (err: any) => {
  return Promise.reject(err)
})

// 响应拦截器
service.interceptors.response.use(async(response: any) => {
  const resData: {
    code: number
    data: any
    message: string
  } = response?.data

  if (resData) {
    // 对返回数据进行预处理
  }

  wx.hideLoading()

  return response
}, (err: any) => {
  wx.hideLoading()

  return Promise.reject(err)
})

export default service

业务接口统一调用 request 实例

// a.ts
import request from '../utils/request'

const res = await request.get({
  url: '/show',
  params: {
    id: 1
  }
})
// b.ts
import request from '../utils/request'

const res = await request.post({
  url: '/create',
  data: {
    name: 'aaaa'
  }
})
1.0.7

11 months ago

1.0.6

11 months ago

1.0.4

12 months ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago