登录页面,鸿蒙实现

193 阅读2分钟

安装第三方库axios

通过ohmp下载第三方库axios

封装http请求类,使用axios拦截器添加错误提示已经成功提示,方便开发使用


import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';
// 创建实例
import { promptAction } from '@kit.ArkUI';
import { BASE_URL, LOGIN_INFO, TOKEN } from '../constants/constants';
import { getToken } from '.';

export const axiosInstance = axios.create({
  baseURL: BASE_URL, // 请求基地址
  timeout: 1000 * 20 // 请求超时时间
})

export interface LoginInfoResponse{
  avatar: string,
  name: string,
  number: string,
  phone: string
  accessToken?:string
}



// 添加请求拦截器
axiosInstance.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
  let token=await getToken()
  if (token) {
    config.headers.set('Authorization', token.toString())
  }
  console.info('1. axios请求拦截', JSON.stringify(config))
  // 对请求数据做点什么
  return config;
}, (error: AxiosError) => {
  console.error('2. axios请求拦截-error', JSON.stringify(error))
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axiosInstance.interceptors.response.use((response: AxiosResponse) => {
  console.warn('3. axios响应拦截', JSON.stringify(response))
  if (response.data?.code === 400) {
    promptAction.showToast({ message: response.data.msg })
    return Promise.reject()
  }
  // 对响应数据做点什么
  return response;
}, (error: AxiosError) => {
  console.error('4. axios响应拦截-error', JSON.stringify(error))
  //AlertDialog.show({ message: '4. axios响应拦截-error' + JSON.stringify(error, null, 2) })
  if (Number(error.code) === 2300060) {
    promptAction.showDialog({
      message: '您的网络好像有点问题,或者您未授予网络权限,请检查后再试!',
      alignment: DialogAlignment.Center,
      buttons: [
        { text: '确认', color: 'rgb( 75,110,175)' }
      ]
    })
  }
  // 对响应错误做点什么
  return Promise.reject(error);
});

export interface ResponseData<T> {
  code: number
  msg: string
  data: T
  tips?: string
  resTime?: string
}

export type AxiosResponseData<T, D = null> = AxiosResponse<ResponseData<T>, D>

使用首选项,持久化token和用户数据

import { LoginInfoResponse } from '.'
import { LOGIN_INFO, LOGIN_INFO_STORE, TOKEN, TOKEN_STORE } from '../constants/constants'
import { preferences } from '@kit.ArkData'

export const initToken= ()=>{
  const tokenStore =preferences.getPreferencesSync(getContext(),{name:TOKEN_STORE})
  return tokenStore
}

export const getToken= async ()=>{
  const tokenStore =initToken()
  return await tokenStore.get(TOKEN,"string")
}

export const setToken = async (token:string) =>{
  const tokenStore =  initToken()
  await tokenStore.put(TOKEN,token)
  tokenStore.flush()
}

export const initUser= ()=>{
  const userStore =preferences.getPreferencesSync(getContext(),{name:LOGIN_INFO_STORE})
  return userStore
}

export const setUser= async (user:LoginInfoResponse)=>{
  const userStore=initUser()
  await userStore.put(LOGIN_INFO,JSON.stringify(user))
  userStore.flush()
}

export const getUser= async ()=>{
  const userStore=initUser()
  const res= await userStore.get(LOGIN_INFO,"string")
  return JSON.parse(res.toString()) as LoginInfoResponse
}

登录页面布局

import { AxiosResponse } from '@ohos/axios'
import { ResponseData } from 'common/src/main/ets/utils/http'
import { login } from '../common/http/login'
import { promptAction, router } from '@kit.ArkUI'
import { TOKEN } from 'common/src/main/ets/constants/constants'
import { getToken, setToken } from 'common/Index'

@Entry
@Component
struct Login {

  @State phone:string='wuyikuaile'
  @State pass:string='123456'

  build() {
    Column({space:30}){
      TextInput({placeholder:'手机号码',text:$$this.phone}).width('100%')
      TextInput({placeholder:'密码',text:$$this.pass}).width('100%')
      Button('登录').width('100%')
        .onClick(async ()=>{
          const res:AxiosResponse<ResponseData<string>>= await login(this.phone,this.pass)

          if(res.status===200){
            setToken(res.data.data)
            router.pushUrl({url:'pages/Index'})
          }
        })
    }.width('100%')
    .padding(20)
    .height('100%')
  }

}

image.png

首页布局

import { TOKEN } from 'common/src/main/ets/constants/constants';
import { promptAction } from '@kit.ArkUI';
import { getToken } from 'common/Index';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  async onPageShow(): Promise<void> {
    let token=await getToken()
    promptAction.showDialog({message:`token:${token}`})
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

image.png

感兴趣的小伙伴可以看一下我的gitee地址

"gitee.com/liuhaobi/dr…"