Http请求
简单封装axios
,支持get
、post
、put
、delete
和patch
方法,promise 的 HTTP 库。更多查看axios文档
基本使用
this.$mk.http.request(config)
this.$mk.http.get(url[, config])
this.$mk.http.delete(url[, config])
this.$mk.http.head(url[, config])
this.$mk.http.options(url[, config])
this.$mk.http.post(url[, data[, config]])
this.$mk.http.put(url[, data[, config]])
this.$mk.http.patch(url[, data[, config]])
例子
window.$mk.http.get('/api/get').then((data) => {
console.log('mock模拟数据')
console.log(data)
console.log('mock模拟数据')
})
})
</script>
全局配置
import axios from 'axios'
import request from './requestInterceptors'
import response from './responseInterceptors'
axios.defaults.withCredentials = true
const http = axios.create({
headers: {},
responseType: 'json',
timeout: 1000 * 10
})
http.interceptors.request.use(request.onFulfilled, request.onRejected)
http.interceptors.response.use(response.onFulfilled, response.onRejected)
export default http
请求拦截
import axios, { AxiosRequestConfig } from 'axios'
export default {
onFulfilled: (config: AxiosRequestConfig<any>) => {
config.cancelToken = new axios.CancelToken((c) => {
// ! 全局没挂上设置默认值
if (!window._cancelHttpArr) window._cancelHttpArr = []
// TODO 把请求push进去便于取消请求
window._cancelHttpArr.push(c)
})
return config
},
onRejected: (error: any) => Promise.reject(error)
}
响应拦截
import axios, { AxiosResponse } from 'axios'
import CODE from './code'
export default {
onFulfilled: (response: AxiosResponse<any, any>) => {
if (response.data?.code === CODE.OK) return Promise.resolve(response.data)
return Promise.reject(response.data)
},
onRejected: (error: any) => {
if (axios.isCancel(error)) return Promise.reject(error)
return Promise.reject(error)
}
}
code码
具体码值根据你项目自行修改
enum code {
OK = 2000, // 服务正常,且返回数据
ERR = 4000, // 参数错误
LOGINERR = 4001, // 用户登陆认证失败
DATAERR = 4002, // 数据不是最新,需刷新
AUTHERR = 4003, // 无权限操作
ERR404 = 4004, // 找不到资源
TOKENERR = 401, // token验证错误
SERVERERR = 5000, // 服务端异常
OTHERERR = 6000 // 未知错误
}
export default code
取消请求
细心的你肯定,发现在请求拦截中使用了window._cancelHttpArr
存储c
方便取消请求,响应拦截axios.isCancel(error)
处理取消请求错误,具体使用工具函数会介绍。