huangye-parking/miniapp/utils/request.js
2026-03-10 17:56:32 +08:00

100 lines
2.4 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.

/**
* 网络请求封装
* 统一处理 Token 注入、错误提示、401 自动跳转登录
*/
// 后台 API 基础地址,按环境配置
// const BASE_URL = 'http://localhost:5030'
const BASE_URL = 'https://api.pli.shhmkjgs.cn'
// 请求超时时间(毫秒)
const TIMEOUT = 10000
/**
* 封装 uni.request
* @param {Object} options - 请求配置
* @param {string} options.url - 接口路径(不含 BASE_URL
* @param {string} [options.method='GET'] - 请求方法
* @param {Object} [options.data] - 请求参数
* @param {boolean} [options.auth=true] - 是否需要携带 Token
* @returns {Promise<any>} 响应数据
*/
export function request(options) {
const { url, method = 'GET', data, auth = true } = options
const header = {
'Content-Type': 'application/json'
}
// 注入 Token
if (auth) {
const token = uni.getStorageSync('token')
if (token) {
header['Authorization'] = `Bearer ${token}`
}
}
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + url,
method,
data,
header,
timeout: TIMEOUT,
success: (res) => {
const { statusCode, data: resData } = res
// 401 未授权,清除登录态
if (statusCode === 401) {
uni.removeStorageSync('token')
uni.removeStorageSync('userInfo')
return reject(new Error('未授权'))
}
// 其他非 2xx 状态码
if (statusCode < 200 || statusCode >= 300) {
const msg = (resData && resData.message) || '请求失败'
uni.showToast({ title: msg, icon: 'none' })
return reject(new Error(msg))
}
resolve(resData)
},
fail: (err) => {
uni.showToast({ title: '网络异常,请稍后重试', icon: 'none' })
reject(err)
}
})
})
}
/**
* GET 请求快捷方法
*/
export function get(url, data, options = {}) {
return request({ url, method: 'GET', data, ...options })
}
/**
* POST 请求快捷方法
*/
export function post(url, data, options = {}) {
return request({ url, method: 'POST', data, ...options })
}
/**
* PUT 请求快捷方法
*/
export function put(url, data, options = {}) {
return request({ url, method: 'PUT', data, ...options })
}
/**
* DELETE 请求快捷方法
*/
export function del(url, data, options = {}) {
return request({ url, method: 'DELETE', data, ...options })
}
export default { request, get, post, put, del }