(ps:uni-app使用时,只需要将wx.request替换成uni.request 即可)
一、结构目录
request文件夹
config.js 配置文件
index.js 请求入口文件
二、config.js
export default{
// 请求基础地址
baseUrl:'',
options:{
header:{"Content-type":"application/json"}
},
interceptor:{
request:function(config){
// 请求参数处理
return config
},
response:function(response){
// 响应数据处理
return response
}
}
}
三、index.js
import config from './config.js'
// 默认请求数据的处理
function Http() {
const {
interceptor,
options,
baseUrl
} = config
this.interceptor = interceptor
this.baseUrl = baseUrl
this.options = Object.assign({}, {
method: 'GET',
data: {},
header: {},
success: function() {},
fail: function() {},
complete: function() {}
}, options)
}
let task = null
Http.prototype.abort = function() {
if (task) {
task.abort()
}
}
Http.prototype.request = function(options) {
options.url = this.baseUrl + options.url
const self = this
return new Promise((resolve, reject) => {
options.complete = function(response) {
const statusCode = response.statusCode
let newResponse = response
if (typeof self.interceptor.response == 'function') {
newResponse = self.interceptor.response(newResponse)
}
if (statusCode == 200) {
resolve(newResponse)
} else {
reject(newResponse)
}
}
let newOptions = Object.assign({}, self.options, options)
if (typeof self.interceptor.request == 'function') {
newOptions = self.interceptor.request(newOptions)
}
wx.request(newOptions)
})
}
const https = new Http()
const requestMethod = ['get', 'post', 'put', "patch", 'head', 'options', 'delete']
const request = (options) => {
if (typeof options == "string") {
options = {
url: options,
method: "GET"
};
} else if (typeof options == "object") {
options.method ? options.method.toUpperCase() : (options.method = "GET");
if (options.method == "GET" && options.data) {
options.params = {
...options.data
};
}
}
return https.request(options);
};
requestMethod.forEach((method) => {
request[method] = (url, data) => {
return request({
url,
method: method.toLowerCase(),
data,
});
};
});
export default request;