鸿蒙接口封装

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

        })
相关推荐
Lee_xiaoming12 小时前
ArkTS基础语法 |(3)类和接口
arkts
SpringSir13 小时前
鸿蒙 文字右侧的小红点
鸿蒙
心中有国也有家1 天前
Flutter for OpenHarmony:Flutter 图像渲染核心Image 组件详解
开发语言·前端·flutter·华为·harmonyos·鸿蒙
加农炮手Jinx2 天前
Flutter for OpenHarmony 实战:built_collection 全链路不可变集合模型
网络·flutter·华为·harmonyos·鸿蒙
加农炮手Jinx2 天前
Flutter for OpenHarmony 实战:url_launcher 插件 — 跨应用跳转与系统集成
flutter·harmonyos·鸿蒙
Lee_xiaoming3 天前
ArkTS基础语法 |(2)函数
arkts
●VON3 天前
HarmonyOS应用开发实战(基础篇)Day02-《ArkTS函数》
学习·harmonyos·鸿蒙·基础知识·von
加农炮手Jinx3 天前
Flutter for OpenHarmony 实战:sensors_plus 传感器融合与 3D 体感交互
网络·flutter·3d·华为·交互·harmonyos·鸿蒙
全栈探索者3 天前
useState 换个名字叫 @State,仅此而已
react·harmonyos·arkts·前端开发·deveco studio·状态管理·鸿蒙next
全栈探索者3 天前
useContext 退场,@Provide + @Consume 登场
react.js·harmonyos·arkts·状态管理·前端转型