鸿蒙开发——网络请求封装request

import axios, { RawAxiosRequestHeaders, AxiosResponse, Method, InternalAxiosRequestConfig } from "@ohos/axios"
import { PostUserInfoPayLoad } from '../types/Api'

export class AxiosUtil {
  private static instance: AxiosUtil = new AxiosUtil()

  private constructor() {
    // 请求拦截器
    axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      // config.headers['Content-Type'] = 'application/json'
      config.headers['authorization'] = (AppStorage.get("userinfo") as PostUserInfoPayLoad)?.token
      // config.headers['authorization'] =
      //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6Ium7mOiupOeUqOaItyIsImF2YXRhciI6ImFjZTQxMTU3NDNkNTgxYjYwYjM0ZjlhOTM0NTVlNTFjLmpwZWciLCJhdmF0YXIyIjoiaHR0cDovL3RtcDAwMDAyLmxlYXJ2LmNvbS9hY2U0MTE1NzQzZDU4MWI2MGIzNGY5YTkzNDU1ZTUxYy5qcGVnIiwib3BlbmlkIjoib010a281RE9QTktQLXVXRDVTZzMwdzlfTzQ3TSIsInVzZXJfaWQiOjUsImlhdCI6MTY5OTg3MTY4NX0.lm6kd0AhNnaXV-9SXu1xXkfTWZ0LTSX0zGTk6am0tsc"
      return config
    })
    // 响应拦截器
    axios.interceptors.response.use((response: AxiosResponse) => {
      return response.data
    })
  }

  // axios: AxiosInstance
  create(baseUrl?: string) {
    axios.defaults.baseURL = baseUrl
    console.log(axios.defaults.baseURL)
  }

  public static getInstance(url: string) {
    AxiosUtil.instance.create(url)
    return AxiosUtil.instance
  }

  async request<D, T>(method: Method = 'get', path: string, data?: D, headers?: RawAxiosRequestHeaders): Promise<T> {
    return await axios.request({
      url: path,
      method,
      data,
      headers
    })
  }

  async post<D, T>(path: string, data?: D, headers?: RawAxiosRequestHeaders): Promise<T> {
    return await axios.post(path, data, { headers })
  }

  async get<T>(path: string, headers?: RawAxiosRequestHeaders): Promise<T> {
    return await axios.get(path, { headers })
  }
}

export const Request = AxiosUtil.getInstance('http://xxx')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值