二次封装axios工具类ES6
2019-01-17 本文已影响10人
苏茶茉芳_亚泽伊
内容概要
使用es6的class对axios进行二次封装,有使用TS限制类型,但99%是js语法。把参数的类型限制移除就是单纯的js。支持JSON,FormData形式的数据提交,支持JSON,Blob形式的数据响应。
分析
我写了一个request父类,包含4个方法,登录判断,响应数据处理,错误信息处理,初始化请求配置。
按响应数据的类型分为,requestData与requestBlob两个子类,每个子类再按照method与发送数据类型的不同设置静态方法。
类的封装
私有数据准备, baseUrl从项目配置文件读取,然后按照 是否做字符串预处理 初始化两种axios
/* Take the baseurl from the configuration file */
// @ts-ignore
let baseUrl = config.baseUrl
/* Initialize axios, do string conversion processing */
let myAxiosPostJson = axios.create({
baseURL: baseUrl,
timeout: 15000,
transformRequest: [(data) => {
return JSON.stringify(data)
}]
})
/* Initialize axios, don't do string conversion processing */
let myAxiosPostForm = axios.create({
baseURL: baseUrl,
timeout: 15000
})
request父类代码
class request {
constructor() {
}
/* According to the agreement with the background developer, whether to log in or not */
static hasLogin(res) {
return !res.data.bizCode && !res.data.success
}
/* Preprocess the returned information */
static processResult(res, response) {
if (this.hasLogin(res)) {
alert(res.data.msg ? res.data.msg : '网络或系统错误')
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath} // 登录成功后跳入浏览的当前页面
})
} else if (res.data.success) {
response(res.data)
} else {
alert(res.data.msg ? res.data.msg : '后台未提示错误信息')
}
}
/* Preprocessing error information */
static processError(err, response) {
let str = err + ''
if (str.search('timeout') !== -1) { // 超时error捕获
alert('请求超时')
} else {
alert(err.data ? err.data.msg ? err.data.msg : '网络或系统错误.' : '网络或系统错误')
}
response(err)
}
/* Initialize the request configuration */
static initConfig(method, url, params, headers, responseType, contentType) {
return {
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
headers: Object.keys(headers).length ? headers : contentType === 'json' ? {
'Content-Type': 'application/json;charset=utf-8'
} : contentType === 'formData' ? {
'Content-Type': 'multipart/form-data'
}: {
'Content-Type': 'application/json;charset=utf-8'
},
responseType: responseType
}
}
}
requestData子类(省略部分代码)
export class requestData extends request {
constructor() {
super()
}
static postJson(url: string, params: object, headers: object, response: object) {
if (store.state.isLoading) {
return
}
myAxiosPostJson(this.initConfig('POST', url, params, headers, 'json', 'json')).then(res => {
this.processResult(res, response)
}).catch(err => {
this.processError(err, response)
})
}
static getJson(url: string, params: object, headers: object, response: object) {......}
static postForm(url: string, formData: object, headers: object, response: object) {......}
static getForm(url: string, formData: object, headers: object, response: object) {
if (store.state.isLoading) {
return
}
myAxiosPostForm(this.initConfig('GET', url, formData, headers, 'json', 'formData')).then(res => {
this.processResult(res, response)
}).catch(err => {
this.processError(err, response)
})
}
}
requestBlob子类(因为基本结构与上一个子类相同,所以本子类简略展示)
export class requestBlob extends request {
constructor() {
super()
}
static postJson(url: string, params: object, headers: object, response: any) {
if (store.state.isLoading) {
return
}
myAxiosPostJson(this.initConfig('POST', url, params, headers, 'blob', 'json')).then(res => {
response(res)
}).catch(err => {
this.processError(err, response)
})
}
static getJson(url: string, params: object, headers: object, response: any) {......}
static postForm(url: string, formData: object, headers: object, response: any) {......}
static getForm(url: string, formData: object, headers: object, response: any) {......}
}
使用例
HelloWorld.vue
<script lang="ts">
import {requestData, requestBlob} from "../../myAxios/axios"
export default {
name: 'HelloWorld',
data () {
return {......},
methods: {
testAxios () {
let params = {
userMobile: 'admin',
password: 'admin'
}
requestData.getJson('http://...../....../....../login', params, {}, res => {
console.log(res)
})
}
}
</script>
如想省略每个单文件组件的引入,也可设置全局属性(如下)
main.ts
import {requestData, requestBlob} from './myAxios/axios'
Vue.prototype.$requestData = requestData
Vue.prototype.$requestBlob = requestBlob
HelloWorld.vue
<script lang="ts">
testAxios () {
let params = {
userMobile: 'admin',
password: 'admin'
}
this.$requestData.getJson('http:/....../login', params, {}, res => {
console.log(res)
})
}
</script>