黑馬程序員前端微信小程序開發(fā)教程,微信小程序從基礎(chǔ)到發(fā)布全流程_企業(yè)級商城實(shí)戰(zhàn)(

// 對請求的封裝
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: '數(shù)據(jù)請求中',
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
}
// 響應(yīng)攔截器
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('需要認(rèn)證')
}
})
// 響應(yīng)攔截器
responseFilter((result) => {
if (result.data.meta.status == 200) {
uni.$showMsg('數(shù)據(jù)請求成功', 500)
return result.data.message
} else {
uni.$showMsg()
}
})
const httpRequest2 = (params) => {
return RC.request(params)
}
export {
httpRequest2
}