鸿蒙开发 03 封装 @ohos/axios (最新深度封装)

鸿蒙开发 03 封装 @ohos/axios (最新深度封装)

  • [1、安装 @ohos/axios](#1、安装 @ohos/axios)
  • 2、开始封装
    • [2.1 新建 utils 文件夹 和 api 文件夹](#2.1 新建 utils 文件夹 和 api 文件夹)
    • [2.2 在 utils 文件夹里新建 http.ts](#2.2 在 utils 文件夹里新建 http.ts)
    • [2.3 在 api 文件夹里新建 api.ets](#2.3 在 api 文件夹里新建 api.ets)
  • 3、页面调用
  • 4、打印结果

1、安装 @ohos/axios

ts 复制代码
ohpm install @ohos/axios

Tips:按住Ctrl + Alt + Shift + S 可以查看你的 SDK 版本,如果你不是最新版(api 12)的话请降低 axios 的版本,不然会爆下面的错误:
ERROR: Failed :entry:default@MergeProfile...

hvigor ERROR: The compatibleSdkVersion 9 cannot be smaller than version 12 declared in library [:library]

as the library might be using APIS not available in 9

hvigor ERROR: BUILD FAILED in 256 ms

c 复制代码
"@ohos/axios": "2.0.0"

2、开始封装

2.1 新建 utils 文件夹 和 api 文件夹

2.2 在 utils 文件夹里新建 http.ts

ts 复制代码
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from "@ohos/axios";

// axios 请求配置
const config = {
  baseURL:'http://localhost:8080',
  // baseURL: '/api',
  timeout: 1000
}

// 定义返回值类型
interface Result<T = any> {
  code: number;
  message: string;
  data: T;
}

class Http {
  // axios 实例
  private instance: AxiosInstance;
  // 构造函数初始化
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    //定义拦截器
    this.interceptors();
  }

  private interceptors() {
    // axios 发送请求之前的处理
    this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      // 在请求头部携带token
      // let token = sessionStorage.getItem('token');
      let token = '';
      if (token) {
        config.headers!['token'] = token;
        // 把 token 放到 headers 里面
        // (config.headers as AxiosRequestHeaders).token = token;
      }
      console.log('' + config);
      return config;

    }, (error: any) => {
      error.data = {};
      error.data.msg = '服务器异常,请联系管理员!'
      return error;
    })
    // axios 请求返回之后的处理
    // 请求返回处理
    this.instance.interceptors.response.use((res: AxiosResponse) => {
      // console.log(res.data);
      if (res.data.code != 200) {
        console.log(res.data.msg || '服务器出错啦');
        return Promise.reject(res.data.msg || '服务器出错啦');
      } else {
        return res.data;
      }
    }, (error) => {
      console.log('进入错误!');
      error.data = {};
      if (error && error.response) {
        switch (error.response.status) {
          case 400:
            error.data.msg = "错误请求";
            console.log(error.data.msg);
            break;
          case 401:
            error.data.msg = "未授权,请登录";
            console.log(error.data.msg);
            break;
          case 403:
            error.data.msg = "拒绝访问";
            console.log(error.data.msg);
            break;
          case 404:
            error.data.msg = "请求错误,未找到该资源";
            console.log(error.data.msg);
            break;
          case 405:
            error.data.msg = "请求方法未允许";
            console.log(error.data.msg);
            break;
          case 408:
            error.data.msg = "请求超时";
            console.log(error.data.msg);
            break;
          case 500:
            error.data.msg = "服务器端出错";
            console.log(error.data.msg);
            break;
          case 501:
            error.data.msg = "网络未实现";
            console.log(error.data.msg);
            break;
          case 502:
            error.data.msg = "网络错误";
            console.log(error.data.msg);
            break;
          case 503:
            error.data.msg = "服务不可用";
            console.log(error.data.msg);
            break;
          case 504:
            error.data.msg = "网络超时";
            console.log(error.data.msg);
            break;
          case 505:
            error.data.msg = "http版本不支持该请求";
            console.log(error.data.msg);
            break;
          default:
            error.data.msg = `连接错误${error.response.status}`;
            console.log(error.data.msg);
        }
      } else {
        error.data.msg = "连接到服务器失败";
        console.log(error.data.msg)
      }
      return Promise.reject(error);
    })
  }
  // GET方法
  get<T = Result>(url: string, params?: object): Promise<T> {
    return this.instance.get(url, { params });
  }
  // POST方法
  post<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.post(url, data);
  }
  // PUT方法
  put<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.put(url, data);
  }
  // DELETE方法
  delete<T = Result>(url: string): Promise<T> {
    return this.instance.delete(url);
  }
}

export default new Http(config);

2.3 在 api 文件夹里新建 api.ets

c 复制代码
// api.ts
import http from '../utils/http';

// 新增
export const testApi = () => {
  return http.get("/admin/term/list")
}

3、页面调用

ts 复制代码
import { testApi } from './api/api'

// 返回数据具体类型
interface term {
  id: number,
  monthCount: number,
  unit: string

}

// 定义返回值类型
interface Result<T = term> {
  code: number;
  message: string;
  data: Array<T>;
}

@Entry
@Component
struct Test7_19Page {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button() {
          Text('发起请求').fontSize(20)
        }.height(200).width(200)
        .onClick(async () => {
          let res: Result = await testApi();
          console.log(JSON.stringify(res.data[0]));
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

4、打印结果

相关推荐
Rysxt_3 小时前
鸿蒙开发语言ArkTS全面介绍
开发语言·华为·harmonyos
前端世界4 小时前
鸿蒙加密存储实战:KeyStore、AES 与真实业务场景解析
华为·harmonyos
花开彼岸天~4 小时前
Flutter跨平台开发:Books 在鸿蒙系统上的使用指南
flutter·华为·harmonyos
前端世界5 小时前
HarmonyOS 分布式身份认证详解:设备是如何“互相信任”的?
分布式·华为·harmonyos
爸爸6195 小时前
Flutter跨平台开发:Multiple Flutters 在鸿蒙系统上的使用指南
flutter·华为·harmonyos
航Hang*6 小时前
第十章:网络系统建设与运维(高级)—— 网络系统安全
网络·华为·ensp·期末·复习
花开彼岸天~6 小时前
Flutter跨平台开发:Android View 在鸿蒙系统上的使用指南
android·flutter·harmonyos
人工智能知识库6 小时前
HCIA-Datacom H12-811题库(带详细解析)
华为·hcia-datacom·题库·h12-811·hcia题库
盐焗西兰花16 小时前
鸿蒙学习实战之路-ArkTS循环渲染_ForEach使用指南
学习·华为·harmonyos
俩毛豆19 小时前
【鸿蒙生态共建】意图框架的使用-通过小艺调起京东发起搜索《精通HarmonyOS NEXT :鸿蒙App开发入门与项目化实战》读者福利
华为·harmonyos·小艺