鸿蒙NEXT实战开发: 依据前端对http请求进行二次简单封装

 一、为什么要对http请求进行封装?

在我看来二次封装有一下几点好处

  • 代码封装之后,开发人员只用关注业务层面的东西,不用去过多浪费时间在接口请求数据处理上。
  • 封装之后代码更加简洁,通俗易懂,方便后期维护,统一管理。
  • 对经验不足的开发人员友好,只需要依葫芦画瓢,参照之前的例子就可以进行开发。
  • 随着团队规模变大,代码封装之后,减少代码冗余,防止屎山代码。
  • 统一处理token修改配置项,统一对数据错误和数据返回进行处理提示等。

二、注意事项

  • 使用HTTP数据请求需要申请ohos.permission.INTERNET权限权,限申请请参考访问控制(权限)开发指导
  • 此次封装功能并没有像axios 里面一样有响应拦截器和请求拦截前。
  • 没有取消重复请求、错误请求重连的功能,所以只适合较小的项目。

三、开始进行封装

1. 创建请求实体类

在ets/common/utils下创建文件request.ets


import http from '@ohos.net.http';

export  interface  httpConfig{
  url:string;
  method:http.RequestMethod;
  timeOut?: number;
  data?: string | Object | ArrayBuffer;
  header?: Object;
  expectDataType?: http.HttpDataType;
}
interface HttpResponse{
   code:string|number;
   message:string;
   data:string|Object|unknown[]
}

export default  (config: httpConfig): Promise<HttpResponse>=> {
  // 创建请求实例
  const service = http.createHttp();


}
2. 对请求实体类进行 Promise 封装

这里面加入了Authorization 身份信息、 Content-Type响应方式、connectTimeout连接超时等 自己需要根据实际业务情况更换


import http from '@ohos.net.http';

export  interface  httpConfig{
  url:string;
  method:http.RequestMethod;
  timeOut?: number;
  data?: string | Object | ArrayBuffer;
  header?: Object;
  expectDataType?: http.HttpDataType;
}
interface HttpResponse{
   code:string|number;
   message:string;
   data:string|Object|unknown[]
}

export default  (config: httpConfig): Promise<HttpResponse>=> {
  // 创建请求实例
  const service = http.createHttp();
  //请求地址
  const url ='http://XXX.XXX' +config.url;

  return new Promise((resolve, reject) => {
    service.request(
      url,
      {
        method: config.method,
        expectDataType: config.expectDataType, //数据类型
        header: {
          "Content-Type":"application/json",
          //header中存放身份信息
          Authorization:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
          ...config.header,
        },
        extraData: config.data,
        readTimeout:config.timeOut|| 50000,
        connectTimeout:config.timeOut|| 50000
      },
      (err, response)=>{
        if (!err && response.responseCode === 200) { //请求200
          if (typeof response.result === 'string') {
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值