mengyirong/utils/request.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-09-09 16:53:19 +08:00
import {
toast,
clearStorageSync,
getStorageSync,
useRouter
} from './utils'
import RequestManager from '@/utils/requestManager.js'
let BASE_URL = 'https://loan.dev88.0rui.cn';
BASE_URL = process.env.NODE_ENV === 'production' ? BASE_URL : '/api';
const manager = new RequestManager()
console.log(BASE_URL);
const baseRequest = async (url, method, data = {}, loading = true) => {
const u = getStorageSync('u');
let requestId = manager.generateId(method, url, data)
if (!requestId) {
console.log('重复请求')
}
if (!requestId) return false;
return new Promise((reslove, reject) => {
loading && uni.showLoading({
title: '加载中...'
})
uni.request({
url: BASE_URL + url,
method: method || 'GET',
header: {
'token': u.token || '',
'content-type': 'application/json'
},
timeout: 10000,
data: data || {},
complete: () => {
uni.hideLoading()
manager.deleteById(requestId)
},
success: (successData) => {
const res = successData.data;
if (successData.statusCode == 200) {
reslove(res)
} else {
toast('网络连接失败,请稍后重试')
reject(res)
}
},
fail: (msg) => {
toast('网络连接失败,请稍后重试')
reject(msg)
}
})
})
}
const request = {};
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})
export default request