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

1、安装 @ohos/axios

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

"@ohos/axios": "2.0.0"

在这里插入图片描述

2、开始封装

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

在这里插入图片描述

2.2 在 utils 文件夹里新建 http.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 = {
   
   
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

她似晚风般温柔789

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值