buddhism/utils/request.js
2025-07-29 11:23:21 +08:00

151 lines
3.6 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 { getTempToken, shouldUseTempToken } from '@/config/dev.js'
const BASE_URL = 'http://192.168.2.7:4501'
/**
* 统一请求方法
* @param {Object} options - 请求配置
* @param {string} options.url - 请求地址
* @param {string} options.method - 请求方法
* @param {Object} options.params - 查询参数
* @param {Object} options.data - 请求体数据
* @param {Object} options.header - 请求头
* @returns {Promise} 返回请求结果
*/
export function request(options = {}) {
return new Promise((resolve, reject) => {
// 获取token优先使用本地存储的token如果没有则使用临时token
const localToken = uni.getStorageSync('token')
let token = localToken
// 如果本地没有token且启用了临时token则使用临时token
if (!token && shouldUseTempToken()) {
token = getTempToken()
console.log('使用临时token进行开发测试')
}
// 构建请求配置
const requestOptions = {
url: BASE_URL + options.url,
method: options.method || 'GET',
header: {
'Content-Type': 'application/json',
...options.header
},
success: (res) => {
// 请求成功处理
if (res.statusCode === 200) {
resolve(res.data)
} else if (res.statusCode === 401) {
// 认证失败
uni.showToast({
title: '登录已过期,请重新登录',
icon: 'none'
})
setTimeout(() => {
uni.navigateTo({
url: '/pages/login/login'
})
}, 1500)
reject(new Error('认证失败'))
} else {
// 其他错误
uni.showToast({
title: res.data?.msg || '请求失败',
icon: 'none'
})
reject(new Error(res.data?.msg || '请求失败'))
}
},
fail: (err) => {
// 请求失败处理
console.error('请求失败:', err)
uni.showToast({
title: '网络错误',
icon: 'none'
})
reject(err)
}
}
// 添加token到请求头
if (token) {
requestOptions.header.Authorization = token
}
// 添加参数
if (options.params) {
requestOptions.data = options.params
}
if (options.data) {
requestOptions.data = options.data
}
// 发起请求
uni.request(requestOptions)
})
}
/**
* GET请求
* @param {string} url - 请求地址
* @param {Object} params - 查询参数
* @param {Object} header - 请求头
* @returns {Promise} 返回请求结果
*/
export function get(url, params = {}, header = {}) {
return request({
url,
method: 'GET',
params,
header
})
}
/**
* POST请求
* @param {string} url - 请求地址
* @param {Object} data - 请求体数据
* @param {Object} header - 请求头
* @returns {Promise} 返回请求结果
*/
export function post(url, data = {}, header = {}) {
return request({
url,
method: 'POST',
data,
header
})
}
/**
* PUT请求
* @param {string} url - 请求地址
* @param {Object} data - 请求体数据
* @param {Object} header - 请求头
* @returns {Promise} 返回请求结果
*/
export function put(url, data = {}, header = {}) {
return request({
url,
method: 'PUT',
data,
header
})
}
/**
* DELETE请求
* @param {string} url - 请求地址
* @param {Object} header - 请求头
* @returns {Promise} 返回请求结果
*/
export function del(url, header = {}) {
return request({
url,
method: 'DELETE',
header
})
}