sd-ajax

基于axios的ajax业务封装,可用于 SSR

Usage no npm install needed!

<script type="module">
  import sdAjax from 'https://cdn.skypack.dev/sd-ajax';
</script>

README

sd-ajax

基于axios的ajax业务封装,可用于ssr

Installation

$ npm install sd-ajax --save

Demo

import Vue from 'vue'
import { Raven } from 'sd-raven'
import { createAxios, setAjaxDebugState } from 'sd-ajax'

// 是否开启调试
setAjaxDebugState(process.env.NODE_ENV !== 'production')

// 对返回值的处理,如接入raven日志监控等
const options = {
  handleRequestError: err => {
    Raven.captureException(err, {
      extra: {
        type: 'requestError'
      }
    })
  },
  handleResponseData: (data) => {
    Vue.sdAccount && Vue.sdAccount.interceptHttpCode(data.code)
  },
  handleResponseError: (err, config) => {
    Raven.captureException(err, {
      extra: {
        type: 'responseError',
        config
      }
    })
  },
  // 对请求数据的处理
  transformRequest: (data, headers) => {
    data.flag = '1'
    return data
  }
}

export default const api = createAxios({
  timeout: 8000, // default 15000
  baseURL: '//api.shuidichou.com',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // default
  }
}, options)

export const apiWave = createAxios({
  baseURL: '//wave.shuidichou.com'
}, options)

API

  • createAxios 创建一个axios实例

    createAxios(settings, options)

    settings 是axios的相关配置

    options包含5个需自定义的函数:

    • handleRequestData 接收一个requestData参数

    • handleRequestError 接收一个请求失败的err参数

    • handleResponseData

      接收一个响应成功的responseData参数和一个config参数(包含一些api的信息),useRawDatatrue时,只接收一个原始的返回值

    • handleResponseError

      接收一个响应失败的err参数一个config参数(包含一些api的信息,config可能为空),useRawDatatrue时,只接收一个原始的返回值

    • transformRequest

      可以是函数或函数数组,对请求数据的处理,接收两个参数dataheaders

      注意:get请求时,只接收一个参数data

    options还有一些可选参数:

    • AuthorizationKey (String) 默认'AuthorizationV2'
    • tokenKey (String) 默认'token'
    • ignoreErrorCode (Boolean) 是否忽略处理接口自定义错误码,默认不忽略
    • errorCodeKey (String) 自定义接口错误码字段,默认为'code'
    • errorCodeOkValue (Number|String|Array) 自定义接口错误码表示返回正确的值,默认为0
    • setHeaderAuth (Boolean) 默认true,是否设置headers Authorization
    • setBodyAuth (Boolean) 默认true,是否设置body Authorization
    • useRawData (Boolean) 是否使用原始的未经过处理的返回值,默认false
    • userDefinedResponse (Boolean) 是否允许用户返回自定义的response,默认false
    • enableTrace (Boolean) 是否开启请求头部设置 trace 相关字段,默认false
    • traceSampler (0 or 1) 在开启 trace 的基础上,设置采样开关:0为关闭; 1为开启
    • needBase64Keys (Array) 需要做base64编码的头部字段名单,默认为空数组
    • enableBase64 (Boolean) 是否开启对 needBase64Keys 中的头部值进行 base64 编码,默认false
    • getCookieFn (Function) 指定获取 Cookie 的函数,在 SSR 中非常有用,默认为内置的仅用于浏览器中获取 Cookie 的函数。

Other

通过createAxios方法生成的实例的方法说明:

get方法外,其余方法使用同axios

  • get

    .get(url, [params], [config])

    如果想使用跟axios一样的get方法,使用.rawGet替代

在mpvue小程序中的使用

配置

在webpack中配置别名:

resolve: {
  alias: {
    // ....
    'sd-ajax': 'sd-ajax/dist/sd-ajax-mini'
  }
}

用法

发送普通请求

// 发送普通 GET 请求
axios.get('https://www.url.com/api/xx')

// 发送 urlencoded 数据
axios.post('https://www.url.com/api/xx', { nickname: '233' })

// 发送 json 数据
axios.post('https://www.url.com/api/xx', { nickname: '233' }, {
  headers: {
    'Content-Type': 'application/json'
  }
})

上传文件

如果在 POST 请求的数据中出现了 $upload 字段,则将此请求视为上传文件请求

axios.post('https://www.url.com/api/xx', {
  $upload: {
    name: 'avatar',
    filePath: 'wxfile://sometempfilepath'     // 来自 wx.chooseImage 等接口的结果
  },
  // ...其它一起发送的数据
})

下载文件

如果在一个 GET 请求中 responseTypefile, 则将此请求视为下载文件请求. 返回文件的临时路径 (详见小程序开发文档)

注意: 只有此时可以使用 http 协议

axios.get('http://www.url.com', { responseType: 'file' }).then(response => {
  console.log(response.data)    // 输出下载成功的文件的临时路径
})

不支持的选项

注:由于小程序的请求功能有限, 所以不支持以下选项. 如果使用时出现了以下选项, 将直接忽略. 不在此列表中的功能均可使用

  • timeout
  • withCredentials
  • auth
  • xsrfCookieName
  • xsrfHeaderName
  • onUploadProgress
  • onDownloadProgress
  • maxContentLength
  • maxRedirects
  • httpAgent
  • httpsAgent
  • proxy

受限的选项

  • url: 必须指定协议, 并且只能是 http 或 https. 只有下载文件可以用 http
  • method: 只能是小程序支持的方法 (详见小程序开发文档)
  • responseType: 只能是 json, text, file 中的一个