【HarmonyOS Arkts笔记】http网络请求封装

文章详细描述了一个在Node.js项目中,如何使用`common.ts`中的常量定义服务器地址和请求超时时间,以及`request.ts`模块中封装的HTTP请求函数,包括请求头设置、错误处理和接口调用示例。重点展示了如何使用Promise进行异步操作和处理登录接口的实现。
摘要由CSDN通过智能技术生成

common.ts

export default class CommonConstant {
  /**
   * The host address of the server.
   */
  static readonly SERVER: string = '请求接口地址';

  /**
   * The request success code.
   */
  static readonly SUCCESS_CODE: number = 200;

  /**
   * Read timeout.
   */
  static readonly READ_TIMEOUT: number = 50000;

  /**
   * Connect timeout.
   */
  static readonly CONNECT_TIMEOUT: number = 50000;
}

request.ts

import http from '@ohos.net.http';
import CommonConstant from './common';
import Prompt from '@system.prompt';

const request = (url: string, data?: Object, header?: Object,) => {
  return new Promise((resolve, reject) => {
    // 请求头
    let h
    if (header) {
      h = header
    } else {
      h = {
        'Content-Type': 'application/json',
      }
    }

    // 每一个httpRequest对应一个HTTP请求任务,不可复用
    let httpRequest = http.createHttp();

    // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
    // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
    httpRequest.on('headersReceive', (header) => {
      // console.info('header: ' + JSON.stringify(header));
    });

    httpRequest.request(
      // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
      CommonConstant.SERVER + url,
      {
        method: http.RequestMethod.POST,
        // 开发者根据自身业务需要添加header字段
        header: h,
        // 当使用POST请求时此字段用于传递内容
        extraData: data,
        expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
        usingCache: true, // 可选,默认为true
        priority: 1, // 可选,默认为1
        connectTimeout: 60000, // 可选,默认为60000ms
        readTimeout: 60000, // 可选,默认为60000ms
      }, (err, res: any) => {
      if (!err) {
        // data.result为HTTP响应内容,可根据业务需要进行解析
        console.info('Result:' + res.result);
        resolve(JSON.parse(res.result))
      } else {
        console.info('error:' + JSON.stringify(err));
        Prompt.showToast({
          message: JSON.stringify(err)
        })
        return JSON.stringify(err)
        // reject(JSON.stringify(err))
        // 取消订阅HTTP响应头事件
        httpRequest.off('headersReceive');
        // 当该请求使用完毕时,调用destroy方法主动销毁。
        httpRequest.destroy();
      }
    });
  })
}

export default request

接口汇总

import request from "./request"

const loginApi = {
  // 账号登录
  async login(data: object) {
    return await request('/account/login', data, {Token: false})
  }
}

export default loginApi

页面调用

import loginApi from "../../api/login"

loginApi.login({
      account: this.account,
      password: this.password
    }).then((res: any) => {
      if (res.code == 1) {
        console.info(res.data)
      }
    })
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值