| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- import { getToken } from '@/utils/auth'
- const LOGIN_URL = '/pages/login/index'
- /** 避免连续触发多次跳转登录页 */
- let loginRedirecting = false
- function redirectToLoginPage() {
- if (loginRedirecting) return
- loginRedirecting = true
- setTimeout(() => {
- loginRedirecting = false
- }, 2000)
- uni.navigateTo({
- url: LOGIN_URL,
- fail: () => {
- uni.reLaunch({ url: LOGIN_URL })
- }
- })
- }
- /**
- * 调用需登录的接口前校验 Token
- * @returns {boolean} 有 Token 返回 true,否则提示并跳转登录页
- */
- export function ensureApiToken(showToast = true) {
- if (getToken()) {
- return true
- }
- if (showToast) {
- uni.showToast({
- title: '请先登录',
- icon: 'none',
- duration: 1500
- })
- setTimeout(() => redirectToLoginPage(), 400)
- }
- return false
- }
- /**
- * 包装需登录的接口请求:无 Token 时直接 reject,不发起请求
- */
- export function callAuthApi(apiFn) {
- if (!ensureApiToken()) {
- return Promise.reject(new Error('未登录'))
- }
- return apiFn()
- }
|