/*
module:数据交互模块
*/
import axios from 'axios'
/**
* @class 发送请求
* @description 通过 axios 向服务器发送请求,请求前拦截请求,返回后拦截响应,
* @param {undefined} null - 无
* @return {function,function} get, post 请求
* @author juZiBuTian 2023/12/08
* @version 1.0.0
* @example
* new class()
*/
class HttpRequest {
constructor() {
this.baseUrl = process.env.VUE_APP_API_URL
this.timeout = 30000
this.queue = {}
this.state = {
'200': (data) => data,
'201': (data) => console.warn(data),
}
}
setInterceptor(instance, url) {
instance.interceptors.request.use((config) => {
// Object.keys(this.queue).length || //开启loading
//config.headers['X-Access-Token'] = token //设置请求头
//config.headers['Content-Type'] = application/json //设置请求头
let CancelToken = axios.CancelToken
if (this.queue[url]) this.queue[url]()//当前请求未完成再次发起,取消上一次请求,发起新的请求
config.cancelToken = new CancelToken((c) => {
this.queue[url] = c
})
// 将this.queue存到vuex中,路由切换时清空并取消请求;也可以通过url取消某个请求,
return config
})
instance.interceptors.response.use(({ data }) => {
delete this.queue[url]
//Object.keys(this.queue).length || //关闭loading
return this.state[data.code] ?
this.state[data.code](data.data):Promise.reject(data)//判断状态
}, (err) => {
delete this.queue[url]
//Object.keys(this.queue).length || //关闭loading
return Promise.reject(err)
})
}
request(options) {
let instance = axios.create()
let config = {
baseURL: this.baseUrl,
timeout: this.timeout,
...options
}
this.setInterceptor(instance)
return instance(config)
}
/**
* @function 发送请求
* @description 通过 axios.get 向服务器发送请求
* @param {String} url - 请求地址
* @param {Object} params - 请求查询参数
* @param {Object} headers - 请求头
* @param {String} responseType - 下载文件等,设置文本类型 一般为 'blob'
* @return {Promise} 返回接口数据
* @author juZiBuTian 2023/12/08
* @version 1.0.0
* @example
* new class().get(url)
*/
get(url, params = {}, headers = {}, responseType = '') {
return this.request(url, {
params, headers, responseType
})
}
/**
* @function 发送请求
* @description 通过 axios.post 向服务器发送请求
* @param {String} url - 请求地址
* @param {Object} data - 请求体 body 参数
* @param {Object} params - 请求查询参数
* @param {Object} headers - 请求头
* @param {String} responseType - 下载文件等,设置文本类型 一般为 'blob'
* @return {Promise} 返回接口数据
* @author juZiBuTian 2023/12/08
* @version 1.0.0
* @example
* new class().post(url)
*/
post(url, data = {}, params = {}, headers = {}, responseType = '') {
return this.request.post(url, data, { params, headers, responseType })
}
}
export default new HttpRequest
axios 封装,详细注释,你值得一看
于 2023-12-08 14:34:36 首次发布