Read this in other languages: English | 简体中文
Installation
axios-ex
comes with the latest version of axios, so you can install it without the axios
package
$ pnpm install axios-ex
$ npm install axios-ex --save
$ yarn add axios-ex
Usage
General use
import { getCookie, setCookie } from 'js-cool'
import AxiosExtend from 'axios-ex'
function setHeaders(instance) {
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
}
function onRequest(config, options = {}) {
return config
}
function onRequestError(err) {
console.error(err)
}
function onResponse(res, options = {}) {
if (res.data.success) return res.data
return Promise.reject(res.data)
}
function onResponseError(err) {
console.error(err)
}
function onError(err) {
console.error(err)
}
function onCancel(err) {
console.error(err.message)
}
const axiosEx = new AxiosExtend({
unique: true,
retries: 0,
orderly: false,
setHeaders,
onRequest,
onRequestError,
onResponse,
onResponseError,
onError,
onCancel
})
export default options => {
options.unique = options.unique ?? false
options.orderly = options.orderly ?? false
return axiosEx.create(options)
}
Define the delay function for failed retries
-
Customize the retry delay time
const axiosEx = new AxiosExtend({
retryDelay: retryCount => {
return retryCount * 1000
}
})
-
Or use axios-ex
built-in function, exponentialDelay randomly incremented by 0%-50%
import AxiosExtend, { exponentialDelay } from 'axios-ex'
const axiosEx = new AxiosExtend({
retryDelay: exponentialDelay
})
Using with vue2.0
Sometimes we need to use this
(vue instance) inside onRequest
or onResponse
, we can use it like this
import AxiosExtend from 'axios-ex'
let axiosEx = null
function onRequest(config, options = {}) {
return config
}
function onResponse(res, options = {}) {
if (this instanceof Vue) {
this.$loader.hide()
}
if (res.data.success) return res.data
return Promise.reject(res.data)
}
export default options => {
if (!axiosEx)
axiosEx = new AxiosExtend({
onRequest: onRequest.bind(this),
onResponse: onResponse.bind(this)
})
if (this instanceof Vue) {
this.$loader.show()
}
return axiosEx.create(options)
}
Using unpkg CDN
<script src="https://unpkg.com/axios-ex@2.4.0/dist/index.global.prod.js"></script>
Support & Issues
Please open an issue here.
License
MIT