Files
smt/api/request.js
T
nepiedg 031eef9643 aaa
2026-02-23 22:24:29 +08:00

81 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { BASE_URL } from '@/config'
import { storage, SESSION_KEY } from '@/utils/storage'
import { login as authLogin } from './auth'
// 是否为 token 失效(HTTP 401 或 body code 401,如 invalid token
function isInvalidToken(res) {
if (res.statusCode === 401) return true
const body = res.data
if (body && body.code === 401) return true
return false
}
export const request = {
async request(options) {
const sessionKey = storage.get(SESSION_KEY)
const isRetryAfter401 = options._retryAfter401 === true
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
data: options.data,
header: {
'Content-Type': 'application/json',
'Authorization': sessionKey ? `Bearer ${sessionKey}` : ''
},
success: async (res) => {
if (isInvalidToken(res)) {
if (isRetryAfter401) {
reject(new Error(res.data?.message || 'invalid token'))
return
}
try {
await authLogin()
const nextOpts = { ...options, _retryAfter401: true }
resolve(this.request(nextOpts))
} catch (e) {
reject(e)
}
return
}
if (res.statusCode !== 200) {
uni.showToast({
title: res.data?.message || '请求失败',
icon: 'none'
})
reject(new Error(res.data?.message || '请求失败'))
return
}
resolve(res.data)
},
fail: (err) => {
uni.showToast({
title: '网络错误',
icon: 'none'
})
reject(err)
}
})
})
},
get(url, params) {
return this.request({ url, method: 'GET', data: params })
},
post(url, data) {
return this.request({ url, method: 'POST', data })
},
put(url, data) {
return this.request({ url, method: 'PUT', data })
},
delete(url) {
return this.request({ url, method: 'DELETE' })
}
}