HarmonyOS axios 拦截器处理token 及异常

验证用户登录   访问权限控制

需求:

  1. 请求拦截器统一携带 token:开头部分需要拼接 Bearer+空格
  2. 响应拦截器统一处理异常 
  • 400:打印错误信息(登录接口测试)
  • 401:移除用户信息,去登录

import axios, { InternalAxiosRequestConfig, AxiosError, AxiosResponse, AxiosRequestConfig } from '@ohos/axios'
import { promptAction } from '@kit.ArkUI'
import { auth } from './Auth'
import { Logger } from './Logger'

// 增加类型
export interface APIErrorType {
  message: string
  msg: string
  code: string
}

// 实例化 通用配置
const instance = axios.create({
  baseURL: 'https://meikou-api.itheima.net/',
  timeout: 5000
})

// 拦截器配置
// 请求拦截器
// token配置等

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const user = auth.getUser()
  if (user.token) {
    config.headers['Authorization'] = `Bearer ${user.token}`
  }
  return config
}, (error: AxiosError) => {
  return Promise.reject(error)
})


// 添加响应拦截器
// 错误统一处理等

instance.interceptors.response.use((response: AxiosResponse) => {
  return response
}, (error: AxiosError<APIErrorType>) => {
  if (error.response?.status === 401) {
    promptAction.showToast({ message: '登录过期' })
    // 删除用户信息 去登录页
    auth.removeUser()
    router.pushUrl({
      url: 'pages/LoginPage'
    })
  } else {
    promptAction.showToast({ message: error.response?.data.message })
  }
  return Promise.reject(error)
})


export interface HttpResponse<T> {
  code: string
  msg: string
  result: T
}

export type ResponseType<T> = AxiosResponse<HttpResponse<T>>

// 网络请求封装请求方法
export class RequestAxios {
  static get<T>(url: string, config?: AxiosRequestConfig): Promise<ResponseType<T>> {
    return instance.get<null, ResponseType<T>>(url, config)
  }

  static post<T>(url: string, data?: object): Promise<ResponseType<T>> {
    return instance.post<null, ResponseType<T>>(url, data)
  }

  static delete<T>(url: string, data?: object): Promise<ResponseType<T>> {
    return instance.delete<null, ResponseType<T>>(url, data)
  }

  static put<T>(url: string, data?: object): Promise<ResponseType<T>> {
    return instance.put<null, ResponseType<T>>(url, data)
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值