零基础开始学习鸿蒙开发-验证登录跳转读书app首页

目录

开发步骤

        1.新建后端项目提供api接口

        2.新建鸿蒙项目编写界面以及网络接口

        3.编写网络请求组件,然后通过获取文本输入数据发起http请求

        4.需要用到的基础知识:Java,SpringBoot、Mysql,Mybatis(接口端,当然,也可以通过其他方式提供接口,例如python)

1.登录界面(用我之前博客写的,就不再啰嗦了)

2. 注册界面(也是用之前的)

3.http网络请求

4.在发起请求之前,记得在 module.json5 开启网络权限

5.页面注册

6.下面是后端相关接口

7.关于网络请求,鸿蒙要求可能会严格一些,本地127.0.0.1请求不了

        7.1 我们可以尝试一下,把地址改成127.0.1

​编辑         7.2 改成内网映射地址,也就是通过内网穿透出来的地址就可以登录成功.

8.关于内网穿透,我用的是闪库。

9.点击登录后,界面效果

10.注册成功之后,界面效果

11.后台数据库 


开发步骤

        1.新建后端项目提供api接口

        2.新建鸿蒙项目编写界面以及网络接口

        3.编写网络请求组件,然后通过获取文本输入数据发起http请求

        4.需要用到的基础知识:Java,SpringBoot、Mysql,Mybatis(接口端,当然,也可以通过其他方式提供接口,例如python)

1.登录界面(用我之前博客写的,就不再啰嗦了)

import router from "@ohos.router"
import http from '@ohos.net.http';
import promptAction from '@ohos.promptAction';
import  postReqeust from '../utils/HttpUtil';

@Entry
@Component
struct  loginPage{
  //定义用户名
  @State username:string ="";
  //定义密码
  @State password:string ="";
  //定义重复用户名密码
  @State repeatPwd:string ="";
  //判断是否为空的标志
  @State isBlank:boolean=false;
  //提示语
  @State message:string ="";
  //全局URL
  @State URL:string ="http://127.0.0.1:8083";
  //定义颜色的值
  // @ts-ignore
  @State colorParm:Color = Color.Gray;
  //判断输入的参数是否为空方法
    isEmty(username:string,password:string,repeatPwd:string){
     //判断用户名是否为空
     if(username==null ||username==""){
       console.debug("用户名为空----");
       return true;
     }
     if(password==null ||password==""){
       console.debug("密码为空----");
       return true;
     }

     if(repeatPwd==null ||repeatPwd==""){
       console.debug("重复输入密码为空----");
       return true;
     }
  }
  //创建请求的方法

  postReq(){
    //创建http请求
      var  httpReq = http.createHttp();
     console.info("发起请求----")
      httpReq.request("http://ntek44b.nat.ipyingshe.com/login",{
      //定义请求方法
      method:http.RequestMethod.POST,
      //添加请求头
      header:{
        'Content-Type':'application/json',
        'charset':'utf-8'
      },
      //请求数据,用户名,密码
      extraData:{
        "username":this.username,
        "password":this.password,
      },
      connectTimeout:60000,
      readTimeout:72000,
    },(msg,data)=>{
      console.debug("data=={}",JSON.stringify(data))
      //请求成功
      if (msg.code==200){
        this.colorParm = Color.Green;
        this.message ="登录成功!";
      }else {
        // @ts-ignore
        this.colorParm = Color.Red;
        this.message ="登录失败,请检查用户名或密码";
      }
    }
    );
  }
  build() {
    //垂直的容器
    Column({ space: 5 }) {
      Row({space:2}){
        Image($r("app.media.app_icon"))
          .width("100")
          .height("100")
          .margin(50);
      }
      Column({ space: 5 }) {
        //输入框
        TextInput({ placeholder: "请输入用户名" }).type(InputType.Normal)
          .width("300").onChange((username: string) => {
          //通过onChange事件获取用户名
          this.username = username;
          console.debug("username==={}", this.username);
        });
        //密码输入框
        TextInput({ placeholder: "请输入密码" }).type(InputType.Password)
          .width("300").onChange((password: string) => {
          //通过onChange事件获取密码
          this.password = password;
          console.debug("password==={}", this.password);
        });
        //重新确认密码
        TextInput({ placeholder: "请再次输入密码" }).type(InputType.Password)
          .width("300").onChange((repeatPwd: string) => {
          //通过onChange事件获取重复输入的密码
          this.repeatPwd = repeatPwd;
          console.debug("repeatPwd==={}", this.repeatPwd);
        });
        Row({ space: 5 }) {
          Text("提示语:").fontColor(Color.Gray);
          // @ts-ignore
          Text(this.message).fontColor(this.colorParm);
        }
        Row({space:2}) {
          //登录
          Button("登录").width("20%").onClick(async () => {
            //判断是否为空
            this.isBlank = this.isEmty(this.username, this.password, this.repeatPwd);
            if (this.isBlank) {
              this.colorParm = Color.Red;
              this.message = "请检查参数是否为空";
              return;
            } else {
              //判断两次输入的密码是否正确
              if (this.password != this.repeatPwd) {
                this.colorParm = Color.Red;
                this.message = "两次输入的密码不一致";
                return;
              }
            }
            //网络请求数据库验证登录
            //发送异步请求
            postReqeust("http://r3y8xeo.nat.ipyingshe.com/login", this.username, this.password)
              .then(data => {
                // 处理成功的数据
                if (data.responseCode===200) {
                  //成功弹窗
                  promptAction.showToast({
                    // @ts-ignore
                    message: JSON.parse(data.result).msg
                  });
                  router.pushUrl({ url: 'pages/shouye'}).then(() => {
                  }).catch((err) => {
                  });
                }else {
                  promptAction.showToast({
                    message: '账号或者密码错误!' // 弹窗内容
                  });
                }
              })
              .catch(error => {
                promptAction.showToast({
                  message: '请求失败,网络接口有问题!' // 弹窗内容
                });
              });
          }).backgroundColor(Color.Green);
          Button("注册").onClick(() => {

            // 跳转到第二页
            router.pushUrl({ url: 'pages/Register'}).then(() => {
            }).catch((err) => {

            });
          });
        }
      }.height("100%")
      .width("100%")
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.Center)
    }

  }
}

2. 注册界面(也是用之前的)

import router from "@ohos.router"
import http from '@ohos.net.http';
import httpPost from '../utils/HttpUtil';
import  postReqeust from '../utils/HttpUtil';
import promptAction from '@ohos.promptAction';
@Entry
@Component
struct  registePage{
  //定义用户名
  @State username:string ="";
  //定义密码
  @State password:string ="";
  //定义重复用户名密码
  @State repeatPwd:string ="";
  //判断是否为空的标志
  @State isBlank:boolean=false;
  //提示语
  @State message:string ="";
  //全局URL
  @State URL:string ="http://127.0.0.1:8083";
  //定义颜色的值
  // @ts-ignore
  @State colorParm:Color = Color.Gray;
  //判断输入的参数是否为空方法
  isEmty(username:string,password:string,repeatPwd:string){
    //判断用户名是否为空
    if(username==null ||username==""){
      console.debug("用户名为空----");
      return true;
    }
    if(password==null ||password==""){
      console.debug("密码为空----");
      return true;
    }

    if(repeatPwd==null ||repeatPwd==""){
      console.debug("重复输入密码为空----");
      return true;
    }
  }
  //创建请求的方法

  postReq(){
    //创建http请求
    var  httpReq = http.createHttp();
    httpReq.request("http://ntek44b.nat.ipyingshe.com/login",{
      //定义请求方法
      method:http.RequestMethod.POST,
      //添加请求头
      header:{
        'Content-Type':'application/json',
        'charset':'utf-8'
      },
      //请求数据,用户名,密码
      extraData:{
        "username":this.username,
        "password":this.password
      },
      connectTimeout:60000,
      readTimeout:72000,
    },(msg,data)=>{
      console.debug("data=={}",JSON.stringify(data))
      console.debug("请求完成---")
      //请求成功
      if (msg.code==200){
        this.colorParm = Color.Green;
        this.message ="登录成功!";
      }else {
        // @ts-ignore
        this.colorParm = Color.Red;
        this.message ="注册失败,请检查用户名或密码";
      }
    }
    );
  }
  build() {
    //垂直的容器
    Column({ space: 5 }) {
      Row({space:2}){
        Image($r("app.media.app_icon"))
          .width("100")
          .height("100")
          .margin(50);
        Button("返回").onClick(()=>{
          router.back();
        }).width("80").backgroundColor(Color.Green)
      }

      Column({ space: 5 }) {
        //输入框
        TextInput({ placeholder: "请输入用户名" }).type(InputType.Normal)
          .width("300").onChange((username: string) => {
          //通过onChange事件获取用户名
          this.username = username;
          console.debug("username==={}", this.username);
        });
        //密码输入框
        TextInput({ placeholder: "请输入密码" }).type(InputType.Password)
          .width("300").onChange((password: string) => {
          //通过onChange事件获取密码
          this.password = password;
          console.debug("password==={}", this.password);
        });
        //重新确认密码
        TextInput({ placeholder: "请再次输入密码" }).type(InputType.Password)
          .width("300").onChange((repeatPwd: string) => {
          //通过onChange事件获取重复输入的密码
          this.repeatPwd = repeatPwd;
          console.debug("repeatPwd==={}", this.repeatPwd);
        });
        Row({ space: 5 }) {
          Text("提示语:").fontColor(Color.Gray);
          // @ts-ignore
          Text(this.message).fontColor(this.colorParm);
        }
          //注册
          Button("提交注册信息").width("45%").onClick( async () => {
            console.debug("注册")
            //判断是否为空
            this.isBlank = this.isEmty(this.username, this.password, this.repeatPwd);
            if (this.isBlank) {
              this.colorParm =Color.Red;
              this.message = "请检查参数是否为空";
              return;
            } else {
              //判断两次输入的密码是否正确
              if (this.password != this.repeatPwd) {
                this.colorParm =Color.Red;
                this.message = "两次输入的密码不一致";
                return;
              }
            }
            //网络请求数据库验证登录
            //发送异步请求
            postReqeust("http://r3y8xeo.nat.ipyingshe.com/register", this.username, this.password)
              .then(data => {
                // 处理成功的数据
                if (data.responseCode===200) {
                  promptAction.showToast({
                    // @ts-ignore
                    message: JSON.parse(data.result).msg
                    // 弹窗内容
                  });
                }else {
                  promptAction.showToast({
                    message: '注册失败!' // 弹窗内容
                  });
                }
              })
              .catch(error => {
                promptAction.showToast({
                  message: '请求失败,网络接口有问题!' // 弹窗内容
                });
              });
          }).backgroundColor(Color.Green);
      }.height("100%")
      .width("100%")
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.Center)
    }
  }
}

3.http网络请求

/*
 * Copyright (c) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import http from '@ohos.net.http';


// @ts-ignore
export default  function postReqeust(url: string,username:string,password:string) {
  if (!url) {
    return undefined;
  }
  let request = http.createHttp();
  let options = {
    method: http.RequestMethod.POST,
    header: {
      'Content-Type': 'application/json', 'charset': 'utf-8'
    },
    extraData: {
      "username": username,
      "password": password
    },
    readTimeout: 5000,
    connectTimeout: 5000
  } as http.HttpRequestOptions;
  try {
    // 使用 await 等待异步请求的结果
    let result = request.request(url, options);
    // 如果请求成功,处理 result
    // 返回结果或进行其他处理
    return result;
  } catch (error) {
    // 如果请求失败,捕获错误
    // 在这里处理错误,比如重试请求、记录日志或抛出新的错误
    // 你可以选择返回一个错误对象、null、默认值或者重新抛出错误
    // 例如,重新抛出错误以便上层调用者可以处理它
    throw error; // 或者你可以不抛出错误,而是返回一个默认值或错误对象
  }
}



// @ts-ignore
export    function postData(url: string,username:string,password:string) {
  if (!url) {
    return undefined;
  }
  let request = http.createHttp();
  let rs = request.request(
    // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
    url,
    {
      method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
      // 开发者根据自身业务需要添加header字段
      header: {
        'Content-Type': 'application/json'
      },
      // 当使用POST请求时此字段用于传递内容
      extraData: {
        "username": username,
        "password": password
      },
      expectDataType: http.HttpDataType.OBJECT, // 可选,指定返回数据的类型
      usingCache: true, // 可选,默认为true
      priority: 1, // 可选,默认为1
      connectTimeout: 3000, // 可选,默认为60000ms
      readTimeout: 3000, // 可选,默认为60000ms
      usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
    }, (err, data) => {
    if (!err) {
      // data.result为HTTP响应内容,可根据业务需要进行解析
      console.info('Result:' + JSON.stringify(data.result));
      console.info('code:' + JSON.stringify(data.responseCode));
      // data.header为HTTP响应头,可根据业务需要进行解析
      console.info('header:' + JSON.stringify(data.header));
      console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
      // 取消订阅HTTP响应头事件
      request.off('headersReceive');
      // 当该请求使用完毕时,调用destroy方法主动销毁
      request.destroy();
    } else {
      console.info('error:' + JSON.stringify(err));

      request.off('headersReceive');

      request.destroy();
    }
  });
  return rs;
}

4.在发起请求之前,记得在 module.json5 开启网络权限

{
  "module": {
    "name": "entry",
    "type": "entry",
    "description": "$string:module_desc",
    "mainElement": "EntryAbility",
    "deviceTypes": [
      "phone",
      "tablet"
    ],
    "deliveryWithInstall": true,
    "installationFree": false,
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ts",
        "description": "$string:EntryAbility_desc",
        "icon": "$media:icon",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:icon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

5.页面注册

        5.1 在使用页面的时候需要在main_pages.json文件先注册,否则无法使用,即无法跳转。

{
  "src": [
    "pages/Index",
    "pages/Register",
    "pages/home",
    "pages/find",
    "pages/setting",
    "pages/shouye",
    "component/MyMessage"
  ]
}

6.下面是后端相关接口

7.关于网络请求,鸿蒙要求可能会严格一些,本地127.0.0.1请求不了

        7.1 我们可以尝试一下,把地址改成127.0.1

         7.2 改成内网映射地址,也就是通过内网穿透出来的地址就可以登录成功.

8.关于内网穿透,我用的是闪库。

9.点击登录后,界面效果

10.注册成功之后,界面效果

11.后台数据库 

此项目的鸿蒙代码和Java的SpringBoot绑定资源分享在博客。

有不懂的,欢迎私信,购买专栏的优先解答,谢谢大家的支持。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心之所想,行则将至

创作不易,希望大家多多鼓励支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值