You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.7 KiB
JavaScript

import {
getToken
} from './token.js'
import {
useStore
} from '@/store'
export const $post = async ({
url,
data = {}
}, opt) => {
try {
const $store = useStore()
let header = {}
if ('delete_token' in opt && !!opt.delete_token) {
if (header['Authorization']) {
delete header['Authorization']
}
} else {
const token = getToken() ? getToken() : '';
header['Authorization'] = 'Bearer ' + token
}
if ('delete_appid' in opt && !!opt.delete_appid) {
if (data['UNIAPP_APPID']) {
delete data['UNIAPP_APPID']
}
} else {
data['UNIAPP_APPID'] = opt.appid
}
if ('delete_apptype' in opt && !!opt.delete_apptype) {
if (data['UNIAPP_APPTYPE']) {
delete data['UNIAPP_APPTYPE']
}
} else {
data['UNIAPP_APPTYPE'] = opt.app_type
}
let isShowLoading = false
try {
if (!!opt.loading) {
$store.loadingStart()
isShowLoading = true
if ($store.loading === 1) {
try {
uni.showLoading({
title: opt.loading_text
})
} catch (loadingErr) {
console.warn('[axios] showLoading失败', loadingErr)
}
}
}
const res = await uni.request({
url,
method: 'POST',
data,
header
});
return res.data
} finally {
// 使用finally确保一定会清理loading
if (isShowLoading) {
try {
$store.loadingDone()
if ($store.loading === 0) {
uni.hideLoading()
}
} catch (cleanupErr) {
console.warn('[axios] 清理loading失败', cleanupErr)
}
}
}
} catch (e) {
console.error('[axios] 请求失败', e)
if (typeof uni.$lu !== 'undefined' && uni.$lu.toast) {
try {
uni.$lu.toast("请求发生错误")
} catch (toastErr) {
console.warn('[axios] toast失败', toastErr)
}
}
throw e
}
}