| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- /**
- * 请求封装
- * 根据环境自动切换 API 地址
- */
- import { getCurrentConfig, CURRENT_ENV } from '@/config/index.js'
- // 缓存配置
- let configCache = null
- // 初始化配置
- const initConfig = async () => {
- if (!configCache) {
- configCache = await getCurrentConfig()
- console.log('当前环境:', configCache.env, '| API 地址:', configCache.baseUrl)
- }
- return configCache
- }
- // 预加载配置
- initConfig()
- /**
- * 统一请求方法
- */
- export const request = async (options) => {
- // 确保配置已加载
- const config = await initConfig()
- const { baseUrl, timeout, debug } = config
-
- return new Promise((resolve, reject) => {
- // 获取 token
- const token = uni.getStorageSync('token') || ''
-
- if (debug) {
- console.log('Request:', options.method || 'GET', options.url, options.data)
- }
-
- uni.request({
- url: baseUrl + options.url,
- method: options.method || 'GET',
- data: options.data || {},
- header: {
- 'Content-Type': 'application/json',
- 'Authorization': token ? `Bearer ${token}` : ''
- },
- timeout: timeout,
- success: (res) => {
- const { statusCode, data } = res
-
- if (debug) {
- console.log('Response:', statusCode, data)
- }
-
- // HTTP 状态码判断
- if (statusCode === 200) {
- // 业务状态码判断
- if (data.code === 0 || data.code === 200 || data.success) {
- resolve(data)
- } else {
- // 业务错误
- uni.showToast({
- title: data.message || data.msg || '请求失败',
- icon: 'none',
- duration: 2000
- })
- reject(data)
- }
- } else if (statusCode === 401) {
- // 未授权,清除缓存并跳转登录页
- uni.removeStorageSync('userInfo')
- uni.removeStorageSync('token')
- uni.reLaunch({
- url: '/pages/login/login'
- })
- reject({ message: '未授权,请重新登录' })
- } else {
- // 其他错误
- uni.showToast({
- title: '网络请求失败',
- icon: 'none',
- duration: 2000
- })
- reject(res)
- }
- },
- fail: (err) => {
- console.error('Request fail:', err)
- uni.showToast({
- title: '网络连接失败',
- icon: 'none',
- duration: 2000
- })
- reject(err)
- }
- })
- })
- }
- /**
- * 快捷请求方法
- */
- export const get = (url, data) => {
- return request({ url, method: 'GET', data })
- }
- export const post = (url, data) => {
- return request({ url, method: 'POST', data })
- }
- export const put = (url, data) => {
- return request({ url, method: 'PUT', data })
- }
- export const del = (url, data) => {
- return request({ url, method: 'DELETE', data })
- }
- export default request
|