Uniapp 请求拦截器和响应拦截器封装教程
在 Uniapp 中使用封装请求拦截器和响应拦截器可以方便地统一处理请求和响应,提高代码复用性和可维护性。
首先,创建一个 'request.js' 文件,用于封装请求拦截器和响应拦截器:
import Vue from 'vue'
import { baseUrl } from '@/config/env'
const request = (options) => {
// 统一设置请求头
options.header = options.header || {}
options.header['content-type'] = 'application/json'
// 添加 baseUrl
options.url = baseUrl + options.url
// 发起请求
return uni.request(options)
}
// 请求拦截器
uni.addInterceptor('request', {
// 请求前拦截处理
invoke(options) {
uni.showLoading({
title: '加载中...',
mask: true
})
return options
},
// 请求失败拦截处理
fail(error) {
uni.hideLoading()
uni.showToast({
title: '请求失败',
icon: 'none'
})
return Promise.reject(error)
}
})
// 响应拦截器
uni.addInterceptor('response', {
// 响应后拦截处理
invoke(response) {
uni.hideLoading()
const { statusCode, data } = response
if (statusCode === 200) {
return data
} else {
uni.showToast({
title: '请求失败',
icon: 'none'
})
return Promise.reject(data)
}
},
// 响应失败拦截处理
fail(error) {
uni.hideLoading()
uni.showToast({
title: '响应失败',
icon: 'none'
})
return Promise.reject(error)
}
})
Vue.prototype.$request = request
在上面的代码中,我们封装了一个 request 函数,用于发起请求。在 request 函数中,我们统一设置了请求头,添加了 baseUrl,并返回了 uni.request(options) 的结果。
我们还对请求拦截器和响应拦截器进行了封装。请求拦截器用于在发起请求前显示 loading,响应拦截器用于在响应后隐藏 loading,并根据响应状态码进行处理。
最后,在 main.js 中引入 request.js 文件即可:
import Vue from 'vue'
import App from './App'
import './request'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
这样,我们就完成了 Uniapp 中封装请求拦截器和响应拦截器的操作。在发起请求时,我们只需要调用 $request 函数即可。
原文地址: https://www.cveoy.top/t/topic/nnri 著作权归作者所有。请勿转载和采集!