Axios,请求拦截器, 鸿蒙NEXT版

[复制链接]
发表于 2025-3-23 11:20:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
1、第一步创建Axios实例
  1. // 创建实例
  2. export const axiosInstance = axios.create({
  3.   baseURL: 'https://www.baidu.com/', // 请求基地址
  4.   timeout: 1000 * 15 // 请求超时时间
  5. })
复制代码
2、第二步界说Data数据响应的数据类型
  1. // 后端响应基本类型
  2. export interface ServiceResponse<Result> {
  3.   code: string
  4.   msg: string
  5.   result: Result
  6. }
复制代码
3、界说Result数据泛型
  1. // Axios 响应类型 > 后端响应基本类型 > 不同接口响应的类型
  2. export type AxiosResponseData<Result = null, Data = null> = AxiosResponse<ServiceResponse<Result>, Data>
复制代码
4、参加请求拦截器,携带Token访问权限
  1. // 添加请求拦截器
复制代码
  1. axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  2.   const loginInfo = AppStorage.get<UserInfo>(USER_KEY)
  3.   if (loginInfo?.token) {
  4.     config.headers.Authorization = loginInfo?.token
  5.   }
  6.   // 对请求数据做点什么
  7.   return config;
  8. }, (error: AxiosError) => {
  9.   // 对请求错误做些什么
  10.   // AlertDialog.show({ message: JSON.stringify(error.message, null, 2) })
  11.   return Promise.reject(error);
  12. });
复制代码
4、添加响应拦截器
  1. // 添加响应拦截器,AxiosResponse -> AxiosResponseData 书写时有提示
  2. axiosInstance.interceptors.response.use((response: AxiosResponseData) => {
  3.   // 后端能响应结果,但是业务码出现错误,提示后端返回的 msg 信息
  4.   AlertDialog.show({ message: JSON.stringify(response.data, null, 2) })
  5.   if (response.data.code !== '200') {
  6.     promptAction.showToast({ message: response.data.msg })
  7.     // 标记为 reject 失败,防止 await 后续代码执行
  8.     // return Promise.reject(response)
  9.   }
  10.   // 对响应数据做点什么
  11.   return response;
  12. }, (error: AxiosError) => {
  13.   // 服务器响应失败,如 404 找不到路径,服务器错误,无网络的提示 等
  14.   AlertDialog.show({ message: JSON.stringify(error.message, null, 2) })
  15.   if (error.message.includes('404')) {
  16.     promptAction.showToast({ message: '请求错误,请检查 url 路径' })
  17.   }
  18.   else if (error.message.includes('401')) {
  19.     promptAction.showToast({ message: '登录信息无效' })
  20.   }
  21.   // 对响应错误做点什么
  22.   return Promise.reject(error);
  23. });
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表