import type { CustomRequestOptions } from '@/http/types'
import { useTokenStore } from '@/store'
import { getEnvBaseUrl } from '@/utils'
import { stringifyQuery } from './tools/queryString'
import qs from 'qs'
// 请求基准地址
const baseUrl = getEnvBaseUrl()
// 拦截器配置
const httpInterceptor = {
// 拦截前触发
invoke(options: CustomRequestOptions) {
// 如果您使用了alova,则请把下面的代码放开注释
// alova 执行流程:alova beforeRequest --> 本拦截器 --> alova responded
// return options
console.log('invoke')
// 非 alova 请求,正常执行
// 接口请求支持通过 query 参数配置 queryString
if (options.method === 'GET') {
let data: string = ''
if ('data' in options) {
data = qs.stringify(options.data, { allowDots: true })
delete options.data
}
if ('query' in options) {
data = qs.stringify(options.query, { allowDots: true })
delete options.query
}
if (data) options.url = `${options.url}?${data}`
}
// 非 http 开头需拼接地址
if (!options.url.startsWith('http')) {
// #ifdef H5
if (JSON.parse(import.meta.env.VITE_APP_PROXY_ENABLE)) {
// 自动拼接代理前缀
options.url = import.meta.env.VITE_APP_PROXY_PREFIX + options.url
}
else {
options.url = baseUrl + options.url
}
// #endif
// 非H5正常拼接
// #ifndef H5
options.url = baseUrl + options.url
// #endif
// TIPS: 如果需要对接多个后端服务,也可以在这里处理,拼接成所需要的地址
}
// 1. 请求超时
options.timeout = 60000 // 60s
// 2. (可选)添加小程序端请求头标识
options.header = {
...options.header,
}
// 3. 添加 token 请求头标识
const tokenStore = useTokenStore()
const token = tokenStore.updateNowTime().validToken
if (token) {
options.header.Authorization = `Bearer ${token}`
}
return options
},
}
export const requestInterceptor = {
install() {
// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)
},
}
- 发布:2026-02-07 15:35
- 更新:2026-02-07 16:40
- 阅读:20
产品分类: uniapp/App
PC开发环境操作系统: Mac
PC开发环境操作系统版本号: MacOS 26.3 Beta (25D5112c)
手机系统: HarmonyOS NEXT
手机系统版本号: HarmonyOS 6.0.0
手机厂商: 模拟器
手机机型: Nova15
页面类型: vue
vue版本: vue3
打包方式: 云端
项目创建方式: CLI
CLI版本号: 3.0.0-4080720251210001
示例代码:
操作步骤:
使用uni.request 发送请求
使用uni.request 发送请求
预期结果:
使用uni.request 发送请求,应先执行invoke()拦截方法
使用uni.request 发送请求,应先执行invoke()拦截方法
实际结果:
使用 uni.addInterceptor('request', httpInterceptor)拦截后,请求不执行invoke
使用 uni.addInterceptor('request', httpInterceptor)拦截后,请求不执行invoke
bug描述:
【报Bug】鸿蒙Next 使用 uni.addInterceptor('request', httpInterceptor)
请求拦截器不生效,invoke()方法不执行。
改代码在h5 app-andorid经测试都正常。
2 个回复
Ask小助手
【官方评审结论】
反馈完整性
Bug 是否成立
根据知识库:
uni.addInterceptor('request', …)。因此,该现象属于异常,可认定为潜在 bug。
DCloud_UNI_OttoJi - 日常回复 uni-app/x 问题,如果艾特我没看到,请主动私信
关联此问题 https://issues.dcloud.net.cn/pages/issues/detail?id=26158
下个 alpha 会修复
要回复问题请先登录或注册
公告
更多>相关问题