鸿蒙接口封装

ts接口封装代码:

request.ts

TypeScript 复制代码
import prompt from '@system.prompt'
import http from '@ohos.net.http';


export default (methods: string, uri: string, params: object, success: Function) => {
  const httpRequest = http.createHttp();
  const base_url = 'http://192.168.1.8:8080/zh-admin'
  httpRequest.request(
    base_url + uri,
    {
      // @ts-ignore
      method: methods, // 可选,默认为"GET"
      // 开发者根据自身业务需要添加header字段
      header: {
        'Content-Type': 'application/json',
        "Authorization": 'Bearer ' + AppStorage.Get('token') // 请求头携带token
      },
      // 当使用POST请求时此字段用于传递内容
      extraData: params
    }, (err, data) => {
    if (!err) {
      // 打印接口返回结果
      console.info('result:' + data.result);
      // @ts-ignore
      var result = JSON.parse(data.result);
      if (result.code == 200) {
        success(result);
      } else {
        // 如果返回错误则提示错误
        if (result.msg) {
          prompt.showToast({
            message: result.msg
          });
        }
      }
    } else {
      console.error('error:' + JSON.stringify(err));
    }
  });
}

页面调用接口代码:

Login.ets(登录调用接口部分)

TypeScript 复制代码
//引入方法
import Request from '../utils/request'

Button("立即登录").width('100%').backgroundColor('#0070FF').margin({ top: 30 })
        .enabled(isLoginButtonClickable(this.userName,this.password))
        .onClick(()=>{
        //检查是否已勾选同意条款协议
          if(!this.isAgree){
            prompt.showToast({
              message: '请先阅读协议!'
            });
            return
          }
          //写入请求方式、路径参数、请求参数
          Request("POST","/login",{
            username: this.userName,
            password: this.password
          },(res)=>{
            if(res.code==200){
               //将返回的token值存入本地
              AppStorage.SetOrCreate('token', res.token)
              prompt.showToast({
                message: '登录成功!'
              });
              //跳转至首页
              router.pushUrl({
                url: 'pages/Index'
              });
            }
          });

        })
相关推荐
熊猫钓鱼>_>3 小时前
【开源鸿蒙跨平台开发先锋训练营】React Native 工程化实践:Hooks 封装与跨端 API 归一化
react native·react.js·华为·开源·harmonyos·鸿蒙·openharmony
熊猫钓鱼>_>12 小时前
【开源鸿蒙跨平台开发先锋训练营】React Native 性能巅峰:HarmonyOS极致优化实战手册
react native·react.js·华为·开源·harmonyos·鸿蒙·openharmony
ITUnicorn1 天前
【HarmonyOS 6】HarmonyOS 自定义时间选择器实现
华为·harmonyos·arkts·鸿蒙·harmonyos6
俩毛豆1 天前
获得2025年度鸿蒙开发者社区贡献榜单(问答产出榜、文章产出榜)
华为·harmonyos·鸿蒙
熊猫钓鱼>_>1 天前
【开源鸿蒙跨平台开发先锋训练营】Day20 React Native 鸿蒙开发全阶段大复盘:从零到一的跨越
react native·开源·react·harmonyos·鸿蒙·openharmony·native
熊猫钓鱼>_>1 天前
【开源鸿蒙跨平台开发先锋训练营】Day 12:全场景适配与异常防护——构建高可靠的鸿蒙跨端体验
react native·ui·华为·开源·app·harmonyos·鸿蒙
加农炮手Jinx1 天前
Flutter for OpenHarmony 实战:network_info_plus 网络扫描与隐私合规深度适配
网络·flutter·华为·harmonyos·鸿蒙
●VON1 天前
HarmonyOS应用开发实战(基础篇)Day04-《泛型与空值安全》
安全·华为·harmonyos·鸿蒙·von
加农炮手Jinx1 天前
Flutter for OpenHarmony 实战:Injectable — 自动化依赖注入大师
网络·flutter·华为·harmonyos·鸿蒙
熊猫钓鱼>_>1 天前
【开源鸿蒙跨平台开发先锋训练营】Day 13:React Native 开发轻量级页面快速响应实践
人工智能·react native·华为·开源·harmonyos·鸿蒙·移动端