基于微信小程序封装的HTTP请求库。它提供了 GET、POST、PUT、DELETE 四种常用的请求方法,并且支持拦截器功能和基准地址配置。
【代码】基于微信小程序封装的HTTP请求库。它提供了 GET、POST、PUT、DELETE 四种常用的请求方法,并且支持拦截器功能和基准地址配置。
·
// 快捷形式 wx.http.get/post/put/delete(url,data,headers)
// 通用形式 wx.http({ method,url,data,headers })
// 请求拦截器:
// wx.http.interceptors.request.use((config) => { return config })
// 响应拦截器:
// wx.http.interceptors.response.use((res) => { return res })
// 基准地址
// wx.http.baseURL = 'XXX'
function http(config) {
return new Promise((resolve, reject) => {
if (http.baseURL) {
if (config.url.startWith('/')) {
if (http.baseURL.endsWith('/')) {
config.url = http.baseURL.slice(0, 1) + config.url
} else {
config.url = http.baseURL + config.url
}
} else {
if (http.baseURL.endsWith('/')) {
config.url = http.baseURL + config.url
} else {
config.url = http.baseURL + '/' + config.url
}
}
}
config = http.interceptors.request._cb(config)
if (!config.method) {
config.method = 'GET'
}
if (config.headers) {
config.header = config.headers
delete config.headers
}
wx.request({
...config,
success(res) {
res = http.interceptors.response._cb(res)
resolve(res)
},
fail(err) {
err = http.interceptors.response._cb(err)
if (err instanceof Promise) {
resolve(err)
} else {
reject(err)
}
}
})
})
}
http.get = function (url, data, headers) {
return http({
method: 'GET',
url,
data,
headers
})
}
http.post = function (url, data, headers) {
return http({
method: 'POST',
url,
data,
headers
})
}
http.put = function (url, data, headers) {
return http({
method: 'PUT',
url,
data,
headers
})
}
http.delete = function (url, data, headers) {
return http({
method: 'DELETE',
url,
data,
headers
})
}
http.interceptors = {
request: {
_cb: config => config,
use(cb) {
this._cb = cb
}
},
response: {
_cb: res => res,
use(cb) {
this._cb = cb
}
}
}
http.baseURL = undefined
wx.http = http
export default http
更多推荐


所有评论(0)