uni-app写的微信小程序如何实现账号密码登录后获取token(而token的有效器一般是30分钟,当页面在操作时token是不会过去,,离开页面第二天登录时token就是过期状态,因为记住了账号密码就不会操作再次登录,但是这样会出现一个token过期的问题,会导致页面无法获取到参数,导致页面无法正确的拿到相关的内容),并且每天的第一次登录后都会直接获取参数而不是耀重新登录
在app.vue中
<script>
import { login, appgetInfo } from '@/src/api/api.js';
export default {data() {return {lastLeaveTime: null,threshold: 2 * 60 * 60 * 1000, // 2小时};},onLaunch: function() {console.log('App Launch');this.autoLogin();},onShow: function() {// 用户重新进入小程序时,检查是否需要自动登录const currentTime = new Date().getTime();if (this.lastLeaveTime && (currentTime - this.lastLeaveTime) > this.threshold) {this.autoLogin();}},onHide: function() {// 记录用户离开的时间this.lastLeaveTime = new Date().getTime();},methods: {autoLogin() {const username = uni.getStorageSync('userName');const password = uni.getStorageSync('userPassword');if (username && password) {this.login(username, password);}},async login(username, password) {try {const response = await login(username, password);if (response.token) {uni.setStorageSync('token', response.token);uni.switchTab({url: '/pages/mine/mine',});} else {throw new Error('用户名或密码不正确');}} catch (error) {console.error('自动登录失败:', error);uni.showModal({title: '自动登录失败',content: error.message || '用户名或密码不正确',showCancel: false,});}}}
}
</script>
在/pagesA/login/login.vue登录页
<template><view class="login_a"><view class="login_w"><view class="login_s"><view><view class="tit_q">欢迎使用旭普能源管理</view></view><view class="login_x"><uni-forms ref="form" :modelValue="formData"><uni-forms-item label="用户" name="name"><uni-easyinput type="text" v-model="formData.name" placeholder="请输入账号或手机号" /></uni-forms-item><uni-forms-item label="密码" name="password"><uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" /></uni-forms-item><button @click="submitForm" type="primary">登录</button><uni-forms-item label=""><uni-data-checkbox v-model="formData.recall" multiple :localdata="formData.recalls" /></uni-forms-item></uni-forms></view></view></view></view>
</template><script setup lang="ts">
import { reactive, onMounted, computed } from 'vue';
import { login } from '@/src/api/api.js';
const formData = reactive({name: '',password: '',recall: [],recalls: [{ value: 0, text: '记住密码' },],
});
const isRemember = computed(() => formData.recall.includes(0));
onMounted(() => {const savedName = uni.getStorageSync('userName');const savedPassword = uni.getStorageSync('userPassword');if (savedName) {formData.name = savedName;}if (savedPassword) {formData.password = savedPassword;}
});
const submitForm = async () => {if (!formData.name || !formData.password) {uni.showModal({title: '提示',content: '用户名和密码不能为空',showCancel: false,});return;}if (!isRemember.value) {uni.showModal({title: '提示',content: '请选择记住密码,避免忘记密码哦!',showCancel: false,});return;}try {const response = await login(formData.name, formData.password);if (response.token) {uni.setStorageSync('token', response.token);if (isRemember.value) {uni.setStorageSync('userName', formData.name);uni.setStorageSync('userPassword', formData.password);} else {uni.removeStorageSync('userName');uni.removeStorageSync('userPassword');}uni.switchTab({url: '/pages/mine/mine',});} else {throw new Error('用户名或密码不正确');}} catch (error) {uni.showModal({title: '登录失败',content: error.message || '用户名或密码不正确',showCancel: false,});}
};
</script>
在request.js
// 封装 wx.request
const service = (options) => {return new Promise((resolve, reject) => {uni.request({url: 'http://47.104.232.49:80/dev-api/' + options.url, // 替换成你的API地址method: options.method || 'GET', // 请求方法,默认GETdata: options.data || {}, // 请求的数据timeout: 10000, // 请求超时时间header: options.headers || {'Content-Type': 'application/json',},success: (res) => {if (res.statusCode === 200) {resolve(res.data); // 请求成功,返回数据} else {reject(new Error(res.data.msg || '请求失败,状态码:' + res.statusCode));}},fail: (error) => {reject(new Error(error.errMsg || '网络请求失败'));}});});
};
// 请求拦截器函数
const requestInterceptor = (options) => {const token = uni.getStorageSync('token'); // 使用 uni 的内置存储方法if (token) {options.headers = options.headers || {};options.headers.Authorization = `Bearer ${token}`;}return options;
};
// 响应拦截器函数
const responseInterceptor = (response) => {// 可以在此处处理响应结果,比如统一错误处理if (response.statusCode === 401) {uni.showModal({title: '登录过期',content: '您的登录已过期,请重新登录',showCancel: false,success: () => {uni.removeStorageSync('token');uni.removeStorageSync('userName');uni.removeStorageSync('userPassword');uni.reLaunch({url: '/pages/login/login'});}});throw new Error('登录过期');}return response;
};
// 最终封装的请求方法
const request = (options) => {const interceptedOptions = requestInterceptor(options);return service(interceptedOptions).then(responseInterceptor);
};
// 封装GET请求
export const get = (url, data, headers) => {return request({url: url,method: 'GET',data: data,headers: headers});
};
// 封装POST请求
export const post = (url, data, headers) => {return request({url: url,method: 'POST',data: data,headers: headers});
};// 封装PUT请求
export const put = (url, data, headers) => {return request({url: url,method: 'PUT',data: data,headers: headers});
};
// 封装DELETE请求
export const del = (url, data, headers) => {return request({url: url,method: 'DELETE',data: data,headers: headers});
};
export default request;