在项目根目录下新建service文件夹,后续封装的文件放在这个文件夹下。
主要的封装是在LsxmRequest.js中,配置项在config.js中,api.js为接口的统一管理文件,项目接口增多时,可以考虑按照功能块对api.js进行进一步划分成多个模块,最后import到api.js中。
1、利用Symbol特性定义四个私有变量,防止变量污染
const config = Symbol('config')
const isCompleteURL = Symbol('isCompleteURL')
const requestBefore = Symbol('requestBefore')
const requestAfter = Symbol('requestAfter')
2、定义LsxmRequest类并添加默认配置、拦截器与请求方法
class LsxmRequest {
//默认配置
[config] = {
baseURL: '',
header: {
'content-type': 'application/json'
},
method: 'GET',
dataType: 'json',
responseType: 'text'
}
//拦截器
interceptors = {
request: (func) => {
if (func)
{
LsxmRequest[requestBefore] = func
}
else
{
LsxmRequest[requestBefore] = (request) => request
}
},
response: (func) => {
if (func)
{
LsxmRequest[requestAfter] = func
}
else
{
LsxmRequest[requestAfter] = (response) => response
}
}
}
static [requestBefore] (config) {
return config
}
static [requestAfter] (response) {
return response
}
static [isCompleteURL] (url) {
return /(http|https)://([w.]+/?)S*/.test(url)
}
request (options = {}) {
options.baseURL = options.baseURL || this[config].baseURL
options.dataType = options.dataType || this[config].dataType
options.url = LsxmRequest[isCompleteURL](options.url) ? options.url : (options.baseURL + options.url)
options.data = options.data
options.header = {...options.header, ...this[config].header}
options.method = options.method || this[config].method
options = {...options, ...LsxmRequest[requestBefore](options)}
return new Promise((resolve, reject) => {
options.success = function (res) {
resolve(LsxmRequest[requestAfter](res))
}
options.fail= function (err) {
reject(LsxmRequest[requestAfter](err))
}
uni.request(options)
})
}
get (url, data, options