您的当前位置:首页正文

鸿蒙axios封装及使用

2024-05-15 来源:帮我找美食网

一.封装

        使用时将token替换成自己存的token,首选项替换成自己的PreferencesUtils,Logger换成console.log()

import axios, { AxiosResponse ,AxiosError,InternalAxiosRequestConfig,AxiosRequestConfig} from '@ohos/axios';
import  {Logger} from 'common/ets/utils/Logger'
import { PreferencesUtils } from 'common/ets/utils/PreferencesUtils'

 const service = axios.create({
  baseURL: 'https:xxx', // 基地址
  timeout: 5000 ,// 限制响应时间,ms
  // headers: {
  //   contentType: 'application/json'
  // },
})

// 添加请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    Logger.info(`1-请求配置${config.method!}-${config.url}:${JSON.stringify(config.params || config.data)}`)
    // config.headers['Content-Type'] = 'application/json'//通用
    // 在发送请求之前做些什么 token
    const token = PreferencesUtils.getStringData('token')
    if (token) {
      config.headers.Authorization = token
    }
    return config;
  },
  (error: AxiosError) => {
    Logger.info(`请求拦截错误${error}`)
    debugger;
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response:AxiosResponse) => {
    // 对响应数据做点什么
    if (response.data?.code && response.data.code !== 1) {
      AlertDialog.show({
        message: response.data?.msg
      })
      Logger.warn('2-code不等于1:' + JSON.stringify(response.data))
      return Promise.reject(response.data)
    }
    Logger.warn('3-响应成功结果:' + JSON.stringify(response.data))
    // 简化数据返回
    return response.data;
  },
  (error:AxiosError) => {
    // 对响应错误做点什么
    AlertDialog.show({ message: error.response?.status + ':' + error.message })
    Logger.error('4-http响应错误:' + JSON.stringify(error))
    return Promise.reject(error);
  }
);
// 请求封装
export  default  service


二.调用

import  request   from 'common/ets/axios/Index'
export class BannerBean {
  content?: Array<ContentBean> = [];
  code?: number;
}
export class ContentBean {
  authorId?: number;
  channelId?: number;
  comments?: number;
  content?: string;
  editor?: string;
  favors?: number;
  featured?: number;
  id?: number;
  status?: number;
  summary?: string;
  tags?: string;
  thumbnail?: string;
  title?: string;
  views?: number;
  weight?: number;
  business?: string;
  url?: string;
  type?: string;
}

interface Params {

}

// 登录
export function getBanner(data:Params) {
  return  request<Params,BannerBean>({
    url: '地址',
    method: 'post',
    data
  });
}

因篇幅问题不能全部显示,请点此查看更多更全内容

热门图文

Top