// 快捷方法: 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 (http.baseURL.endsWith('/')) {
http.baseURL = http.baseURL.slice(0, -1)
}
if (config.url.startsWith('/')) {
config.url = config.url.slice(1)
}
config.url = http.baseURL + '/' + config.url
}
// if (http.baseURL) {
// if (config.url.startsWith('/')) {
// 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)就是 use函数的回调函数
config = http.interceptors.request._cb(config)
// 不传 method 默认是get
if (!config.method) {
config.method = 'GET'
}
// 转换 headers 为 header,微信小程序需求header而axios需要headers(用户习惯)
if (config.headers) {
config.header = config.headers
delete config.headers
}
// 微信小程序发原生请求
wx.request({
...config,
success(res) {
// 响应拦截器 处理了res
res = http.interceptors.response._cb(res)
// 如果res是promise,resolve会自动区分,会等待其状态改变再执行
// res的结果是成功 resolve就是成功,res的失败 resolve的就是失败
resolve(res)
},
fail(err) {
err = http.interceptors.response._cb(err)
// 如果 err Promise 对象处于成功状态(resolved),则将通过 resolve 函数将该 Promise 的成功值传递下去。
// 如果 err Promise 对象处于失败状态(rejected),则将通过 catch 方法将该 Promise 的错误原因传递下去
// 如果err是 promise ,reject只会原样抛出错误
if (err instanceof Promise) {
resolve(err) // 等待promis的执行结果
} 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.delete = function (url, data, headers) {
return http({
method: 'delete',
url,
data,
headers,
})
}
http.put = function (url, data, headers) {
return http({
method: 'put',
url,
data,
headers,
})
}
// 请求响应拦截器配置
http.interceptors = {
request: {
// 请求拦截器
// use的回调函数,每次发请求时拦截器都会调用_cb,返回一个新的config
_cb: function (config) {
return config
},
// 调用 use函数 传入 新的回调代替_cb()
use: function (cb) {
this._cb = cb
},
},
response: {
// 响应拦截器
_cb: function (res) {
return res
},
use: function (cb) {
this._cb = cb
},
},
}
http.baseURL = 'https://live-api.itheima.net/' // 给一个初始值
// 响应拦截器 数据简化 异常处理
http.interceptors.response.use((res) => {
// 简化数据
const data = res.data
// 异常提示
if (data.code !== 10000) {
wx.utils.toast()
return new Promise.reject(res) // 抛异常 中断逻辑
}
return data
})
// 挂载到 wx全局对象中
wx.http = http
// 提高代码灵活性
export default http
学了一个 微信小程序发请求 支持Promise 的二次封装 记录一下
于 2023-07-22 10:49:26 首次发布