81 lines
1.8 KiB
JavaScript
81 lines
1.8 KiB
JavaScript
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' })
|
||
}
|
||
}
|