自动登录

// 节流自动登录
let lastLoginTime
const autoLogin = (config) => {
	return new Promise((resolve, reject) => {
		const username = getSysStorage(constant.name)
		const password = getSysStorage(constant.password)
		if (lastLoginTime && new Date() - lastLoginTime < 1000) {
			setTimeout(() => {
				request(config).then(resAgain => {
					resolve(resAgain)
				})
			}, 300)
		} else if (username && password) {
			removeToken()
			lastLoginTime = new Date()
			store.dispatch('Login', {
				username,
				password
			}).then(res => {
				getToken() && request(config).then(resAgain => {
					resolve(resAgain)
				})
			}).catch(err => {
				reject(err)
			})
		} else {
			reject({
				code: 500,
				msg: '自动登录失败,请前往登录页登录'
			})
		}
	})
}

  request中:

               if (code === 401) {
					autoLogin(config).then(resAgain => {
						resolve(resAgain)
					}).catch(err => {
						reject(err)
						showConfirm(err.msg || '登录已失效,您可以继续留在该页面,或者重新登录?').then(res => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login'
								})
							}
						})
					})
				}        

  

posted on 2023-10-19 18:19  WhoLovesAbby  阅读(18)  评论(0编辑  收藏  举报