鸿蒙接口封装

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'
              });
            }
          });

        })
相关推荐
三声三视15 小时前
Electron+鸿蒙桌面应用实战:跨平台开发完全指南
electron·harmonyos·鸿蒙·桌面
阿钱真强道2 天前
19 小凌派 rk2206 鸿蒙 LiteOS-M 任务详解
华为·鸿蒙·任务·liteos·详解·rk2206·小凌派
阿钱真强道2 天前
18 小凌派 rk2206 鸿蒙 liteos 如何通过修改配置文件,编译不通的案例
华为·鸿蒙·编译·案例·liteos·rk2206
UnicornDev2 天前
【Flutter x HarmonyOS 6】魔方计时APP——记录页面的UI设计
flutter·ui·华为·harmonyos·鸿蒙
空中海2 天前
03 ArkUI 组件、状态与多端适配
鸿蒙
●VON2 天前
纯ArkUI实现7层拟物3D环形进度图:零依赖的视觉革命
服务器·3d·app·鸿蒙·von
aqi002 天前
一文速览 HarmonyOS 6.0.1 引入的十个新特性
android·华为·harmonyos·鸿蒙·harmony
三声三视3 天前
鸿蒙 ArkTS 国际化实战全攻略:多语言切换、格式本地化与 RTL 布局一步到位
华为·harmonyos·鸿蒙
空中海3 天前
04 Stage 模型、系统能力与数据架构
架构·鸿蒙
●VON3 天前
鸿蒙Widget开发实战:3张卡片实现桌面-App全链路同步
华为·app·harmonyos·鸿蒙·von