鸿蒙接口封装

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

        })
相关推荐
程序员潘Sir2 天前
鸿蒙应用开发从入门到实战(十九):样式复用案例
harmonyos·鸿蒙
程序员潘Sir3 天前
鸿蒙应用开发从入门到实战(十八):组件编程思想之代码复用
harmonyos·鸿蒙
Y学院4 天前
实战项目:鸿蒙多端协同智能家居控制 App 开发全流程
开发语言·鸿蒙
程序员潘Sir4 天前
鸿蒙应用开发从入门到实战(十七):ArkUI组件List&列表布局
harmonyos·鸿蒙
小白学鸿蒙5 天前
OpenHarmony(开源鸿蒙)小白入门教程
harmonyos·鸿蒙·鸿蒙系统
懒惰蜗牛8 天前
鸿蒙开发3--UI布局(玩转鸿蒙的Row、Column与Stack容器)
ui·华为·harmonyos·鸿蒙·鸿蒙系统
_waylau9 天前
如何将鸿蒙5应用升级到鸿蒙6
华为·harmonyos·鸿蒙·鸿蒙系统
ChinaDragonDreamer13 天前
HarmonyOS:固定样式弹出框
harmonyos·鸿蒙
鸿蒙小白龙15 天前
【OpenHarmony实战】系统参数SystemParameter完全指南:param get/set调试技巧与案例精解
harmonyos·鸿蒙·open harmony
鸿蒙小白龙15 天前
OpenHarmony中的系统服务管理配置讲解
harmonyos·鸿蒙·鸿蒙系统·open harmony