鸿蒙接口封装

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

        })
相关推荐
加农炮手Jinx4 小时前
Flutter for OpenHarmony 实战:疯狂头像 App(三)— 复合动画与交互反馈 — 让 UI 跃动起来
flutter·ui·交互·harmonyos·鸿蒙
_waylau1 天前
鸿蒙架构师修炼之道-架构师设计思维特点
华为·架构·架构师·harmonyos·鸿蒙·鸿蒙系统
Betelgeuse761 天前
【Flutter For OpenHarmony】 项目结项复盘
华为·交互·开源软件·鸿蒙
ITUnicorn2 天前
【HarmonyOS 6】进度组件实战:打造精美的数据可视化
华为·harmonyos·arkts·鸿蒙·harmonyos6
阿林来了4 天前
Flutter三方库适配OpenHarmony【flutter_speech】— 原始插件源码分析
flutter·harmonyos·鸿蒙
阿林来了4 天前
Flutter三方库适配OpenHarmony【flutter_speech】— OpenHarmony 插件工程创建
flutter·harmonyos·鸿蒙
_waylau4 天前
跟老卫学仓颉编程语言开发:浮点类型
人工智能·华为·harmonyos·鸿蒙·鸿蒙系统·仓颉
Lee_xiaoming5 天前
ArkTS基础语法 |(4)泛型类型和函数、空安全、模块、关键字、注解
arkts
●VON5 天前
HarmonyOS应用开发实战(基础篇)Day05-《常见布局Row和Column》
学习·华为·harmonyos·鸿蒙·von
阿林来了6 天前
Flutter三方库适配OpenHarmony【flutter_speech】— 开发环境搭建
flutter·harmonyos·鸿蒙