《微信小程序》第五章:登录-API封装

系列文章

《微信小程序》https://blog.csdn.net/sen_shan/category_13069009.html

第五章:登录-简约版本https://blog.csdn.net/sen_shan/article/details/153731482

文章目录

目录

系列文章

文章目录

前言

登录接口结构

API封装

登录页


前言

本文介绍了微信小程序登录功能的简约实现方案。

首先定义了登录接口的响应数据结构(LoginDataResponse)和整体响应格式(LoginResponse),包含token_key、api_key等关键字段。

封装了loginAPI请求方法,处理登录请求并返回Promise。

页面部分实现了包含用户名、密码输入框的基础登录界面,通过onLoad生命周期读取缓存的用户名实现自动回填。

核心login方法调用API后存储token和用户名,并跳转首页。

登录接口结构

建立src\model\login.ts文件

javascript 复制代码
export interface LoginDataResponse {
  api_key: string
  username: string
  token_key: string
  role: string | null
  email: string
}

export interface LoginResponse {
  status_code: number;
  status: string;
  message?: string;
  data?:LoginDataResponse
  }
  1. 文档目的 本文档用于描述「登录接口」返回的 JSON 数据结构,方便前端、客户端及服务端开发人员在对接时快速理解字段含义、类型约束与使用场景。

  2. 适用范围

登录/鉴权模块的所有 HTTP/HTTPS 接口

任何依赖登录态(token_key / api_key)的后续接口

自动化测试脚本、接口文档生成工具

  1. 接口返回总览
javascript 复制代码
{
  "status_code": 200,
  "status": "success",
  "message": "登录成功",
  "data": {
    "api_key": "ae139f8f6a8efc2a74a1e852c5cdaa43",
    "username": "zhangsan",
    "token_key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "role": "admin",
    "email": "zhangsan@example.com"
  }
}
  1. 异常示例
javascript 复制代码
{
	"status_code": 400,
	"status": "error",
	"message": "password is error",
	"data": {
		"api_key": "ae139f8f6a8efc2a74a1e852c5cdaa43",
		"username": "some-login-id6",
		"token_key": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..",
		"role": null,
		"email": "user@example.com"
	}
}

API封装

建立src\api\login.ts文件

javascript 复制代码
import { http } from '@/src/utils/request'
import { LoginResponse,LoginDataResponse } from '@/src/model/login'

  
/* ---------- 类型定义(按后端实际改) ---------- */
export const loginAPI = (data: any): Promise<LoginDataResponse> =>
  http.post<LoginDataResponse>('/login', data)  

loginAPI :对外函数

接收任意类型 data (用户名、密码)

返回Promise<LoginDataResponse>

data: any 丢失了类型约束,具体根据实际情况可以写成:

javascript 复制代码
interface LoginParams { username: string; password: string }
data: LoginParams

请求调用

javascript 复制代码
http.post<LoginDataResponse>('/login', data)

把响应体直接映射成 LoginDataResponse ,参数为data少了一层 response.data 的提取。

登录页

html 复制代码
<template>
  <view class="page">
    <input v-model="form.username" placeholder="账号" />
    <input v-model="form.password" placeholder="密码" password />
    <button @click="login">登录</button>
  </view>
</template>

<script setup lang="ts">
import { reactive  } from 'vue'
import { onLoad } from '@dcloudio/uni-app'  //
// import { http } from '@/src/utils/request'
import { loginAPI } from '@/src/api/login'
import { LoginResponse,LoginDataResponse  } from '@/src/model/login'

const form = reactive({ username: '', password: '' })

/* 生命周期:页面加载时回显上次登录名 */
onLoad(() => {
  const lastUser = uni.getStorageSync('userName') as string | ''
  if (lastUser) form.username = lastUser
})

async function login() {
  if (!form.username || !form.password) return
  try {
	const responseData: LoginDataResponse= await loginAPI(form)
	uni.setStorageSync('token', responseData.token_key)
	uni.setStorageSync('userName', responseData.username)
    uni.reLaunch({ url: '/pages/index/index' })
  } catch {
    // 失败不做任何提示(按你要求)
	console.error('登录失败')
  }
}
</script>

<style scoped>
.page{padding: 200rpx 60rpx}
input{border: 1px solid #ddd;margin: 20rpx 0;padding: 20rpx;border-radius: 8rpx}
button{margin-top: 40rpx}
</style>

生命周期回调

javascript 复制代码
onLoad(() => {
  const lastUser = uni.getStorageSync('userName') as string | ''
  if (lastUser) form.username = lastUser
})

读取本地缓存 userName ,若存在则回显到账号输入框,减少用户重复输入。

核心方法 -- login()

javascript 复制代码
async function login() {
  if (!form.username || !form.password) return
  try {
	const responseData: LoginDataResponse= await loginAPI(form)
	uni.setStorageSync('token', responseData.token_key)
	uni.setStorageSync('userName', responseData.username)
    uni.reLaunch({ url: '/pages/index/index' })
  } catch {
    // 失败不做任何提示(按你要求)
	console.error('登录失败')
  }
}

非空校验

账号或密码为空时直接 return ,不继续请求。

请求接口

await loginAPI(form) ,入参即整个 form 对象(字段名需与后端保持一致)。

缓存令牌

把返回的 token_key 写入 uni.setStorageSync('token') ,供后续业务接口在请求头携带。

缓存用户名

方便下次回显,同时可用于个人中心展示。

跳转首页

uni.reLaunch 关闭所有页面再跳转,避免用户通过返回键再次回到登录页。

相关推荐
2501_9160074719 小时前
iPhone APP 性能测试怎么做,除了Instruments还有什么工具?
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063219 小时前
Windows 环境下有哪些可用的 iOS 上架工具, iOS 上架工具的使用方式
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
iOS 抓包工具有哪些?不同类型的抓包工具可以做什么
android·ios·小程序·https·uni-app·iphone·webview
云起SAAS1 天前
供求求购供应发布VIP会员抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·供求求购供应发布
毕设源码-朱学姐1 天前
【开题答辩全过程】以 基于微信小程序旅游疫情防控管理系统为例,包含答辩的问题和答案
微信小程序·小程序·旅游
weixin_lynhgworld1 天前
陪诊小程序系统开发:开启就医陪伴新体验 [特殊字符]
小程序
weixin_lynhgworld1 天前
旧物回收小程序:让闲置物品焕发新生 ✨
java·开发语言·小程序
一点晖光1 天前
ios底部按钮被挡住
前端·ios·微信小程序
前端程序猿之路2 天前
基于扣子(Coze)工作流 API 的微信小程序开发实践总结
前端·微信小程序·小程序·大模型·api·ai编程·扣子
德育处主任2 天前
在小程序做海报的话,Painter就很给力
前端·微信小程序·canvas