sd-ajax
基于axios的ajax业务封装,可用于ssr
Installation
$ npm install sd-ajax --save
Demo
// 是否开启调试 // 对返回值的处理,如接入raven日志监控等const options = { Raven } { VuesdAccount && VuesdAccount } { Raven } // 对请求数据的处理 { dataflag = '1' return data } const api = const apiWave =
API
-
createAxios
创建一个axios实例createAxios(settings, options)
settings
是axios的相关配置options
包含5个需自定义的函数:-
handleRequestData
接收一个requestData
参数 -
handleRequestError
接收一个请求失败的err
参数 -
handleResponseData
接收一个响应成功的
responseData
参数和一个config
参数(包含一些api的信息),useRawData
为true
时,只接收一个原始的返回值 -
handleResponseError
接收一个响应失败的
err
参数一个config
参数(包含一些api的信息,config
可能为空),useRawData
为true
时,只接收一个原始的返回值 -
transformRequest
可以是函数或函数数组,对请求数据的处理,接收两个参数
data
和headers
;注意:
get
请求时,只接收一个参数data
options
还有一些可选参数:AuthorizationKey
(String) 默认'AuthorizationV2'tokenKey
(String) 默认'token'ignoreErrorCode
(Boolean) 是否忽略处理接口自定义错误码,默认不忽略errorCodeKey
(String) 自定义接口错误码字段,默认为'code'errorCodeOkValue
(Number|String|Array) 自定义接口错误码表示返回正确的值,默认为0setHeaderAuth
(Boolean) 默认true,是否设置headers AuthorizationsetBodyAuth
(Boolean) 默认true,是否设置body AuthorizationuseRawData
(Boolean) 是否使用原始的未经过处理的返回值,默认falseuserDefinedResponse
(Boolean) 是否允许用户返回自定义的response,默认falseenableTrace
(Boolean) 是否开启请求头部设置 trace 相关字段,默认falsetraceSampler
(0 or 1) 在开启 trace 的基础上,设置采样开关:0为关闭; 1为开启needBase64Keys
(Array) 需要做base64编码的头部字段名单,默认为空数组enableBase64
(Boolean) 是否开启对 needBase64Keys 中的头部值进行 base64 编码,默认falsegetCookieFn
(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 // 发送 urlencoded 数据axios // 发送 json 数据axios
上传文件
如果在 POST 请求的数据中出现了 $upload
字段,则将此请求视为上传文件请求
axios
下载文件
如果在一个 GET 请求中 responseType
为 file
, 则将此请求视为下载文件请求.
返回文件的临时路径 (详见小程序开发文档)
注意: 只有此时可以使用 http 协议
axios
不支持的选项
注:由于小程序的请求功能有限, 所以不支持以下选项. 如果使用时出现了以下选项, 将直接忽略. 不在此列表中的功能均可使用
timeout
withCredentials
auth
xsrfCookieName
xsrfHeaderName
onUploadProgress
onDownloadProgress
maxContentLength
maxRedirects
httpAgent
httpsAgent
proxy
受限的选项
url
: 必须指定协议, 并且只能是 http 或 https. 只有下载文件可以用 httpmethod
: 只能是小程序支持的方法 (详见小程序开发文档)responseType
: 只能是json
,text
,file
中的一个