黑马程序员前端微信小程序开发教程,微信小程序从基础到发布全流程_企业级商城实战(

// 对请求的封装
class MyRequest {
static Base = 'http://api-hmugo-web.itheima.net/api'
params = {}
beforeCall = null
afterCall = null
// 请求
async request(params) {
this.params = params
if (this.beforeCall) {
this.beforeCall(this.params)
}
uni.showToast({
duration: 500,
title: '数据请求中',
icon: 'loading'
})
const res = await uni.request({
...params,
url: MyRequest.Base + params.url,
}).catch(err => err)
if (this.afterCall) {
return this.afterCall(res)
}
}
// 请求拦截器
beforeRequest(callback) {
this.beforeCall = callback
}
// 响应拦截器
responseFilter(callback) {
this.afterCall = callback
}
}
const RC = new MyRequest()
const responseFilter = (call) => {
return RC.responseFilter(call)
}
const requestFilter = (call) => {
return RC.beforeRequest(call)
}
// 请求拦截器
requestFilter((params) => {
if (/.*(\/my\/)/.test(params?.url)) {
console.log('需要认证')
}
})
// 响应拦截器
responseFilter((result) => {
if (result.data.meta.status == 200) {
uni.$showMsg('数据请求成功', 500)
return result.data.message
} else {
uni.$showMsg()
}
})
const httpRequest2 = (params) => {
return RC.request(params)
}
export {
httpRequest2
}