官网介绍
业务分析
假设我们不使用这个拦截器, 那么我们的每次请求request可能都需要填写完整的url 可能会把url通用的抽离出来 然后按需引入 但是token,报文,请求超时等信息不可能也要 ,写一个request就要手动加一个timeout把 所以我们可以使用addInterceptor 每当请求要发送,先进入拦截器,对里面的报文数据进行基础的统一处理, 这样request就会更加便捷 那么我们要拦截处理什什么呢
uni.addInterceptor介绍
### uni.addInterceptor(STRING, OBJECT)
添加拦截器STRING
需要拦截的`api`名称,如:`uni.addInterceptor('request', OBJECT)` ,将拦截 `uni.request()`
OBJECT处理函数对象 是一个对象 ,对象里面是处理函数
{
invoke(){
...做点什么
}
}
新建一个文件夹http.ts 搭建基础结构
const httpInterceptor = {
invoke(options: UniApp.RequestOptions) {
//做点什么
},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
1.路径拼接
我们可以同意请求的域名或是ip 当需要切换地址,方便处理
const BaseUrl = 'https://exapmle.com'
const httpInterceptor = {
invoke(options: UniApp.RequestOptions) {
// request 触发前拼接 url
options.url = BaseUrl + options.url
},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
2.超时设置
const BaseUrl = 'https://exapmle.com'
const httpInterceptor = {
invoke(options: UniApp.RequestOptions) {
// request 触发前拼接 url
options.url = BaseUrl + options.url
//超时设置
options.timeout = 10000
},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
3.请求头标识
const BaseUrl = 'https://exapmle.com'
//4.token
const httpInterceptor = {
invoke(options: UniApp.RequestOptions) {
// request 触发前拼接 url
options.url = BaseUrl + options.url
//超时
options.timeout = 10000
//请求头 进行覆盖操作
options.header = {
...options.header,
'source-client': 'miniapp',
}
},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
4.token
const BaseUrl = 'https://exapmle.com'
const httpInterceptor = {
invoke(options: UniApp.RequestOptions) {
// request 触发前拼接 url
options.url = BaseUrl + options.url
//
options.timeout = 10000
options.header = {
...options.header,
'source-client': 'miniapp',
}
//token操作 配置请求报文
const userStore = UseUserStore()
const token = userStore.profile?.token
if (token) {
options.header.Authorization = token
}
},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
使用
在需要的请求页面引入该文件
import "@/http"
结果测试
没有token信息
有token信息