vending-machine/mobile/api/request.js
2026-04-08 21:03:13 +08:00

103 lines
3.0 KiB
JavaScript
Raw Permalink 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 { getStorage, removeStorage, TOKEN_KEY, LOCALE_KEY } from '../utils/storage.js'
// 后端API基础地址
// MuMu模拟器需使用宿主机局域网IP生产环境替换为正式域名
export const BASE_URL = 'http://192.168.21.7:5082'
/**
* 统一请求封装自动注入Token和语言请求头统一处理响应和错误
* @param {string} url - 请求路径(相对路径)
* @param {object} options - 请求选项
* @returns {Promise<{success: boolean, data: any, message: string}>}
*/
export function request(url, options = {}) {
const token = getStorage(TOKEN_KEY)
const locale = getStorage(LOCALE_KEY) || 'zh-CN'
const header = {
'Content-Type': 'application/json',
'Accept-Language': locale,
...options.header
}
if (token) {
header['Authorization'] = `Bearer ${token}`
}
return new Promise((resolve, reject) => {
uni.request({
url: `${BASE_URL}${url}`,
method: options.method || 'GET',
data: options.data,
header,
success: (res) => {
// 401未授权清除Token并跳转登录页
if (res.statusCode === 401) {
removeStorage(TOKEN_KEY)
uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' })
uni.reLaunch({ url: '/pages/login/login' })
reject(new Error('未授权'))
return
}
// 服务器错误
if (res.statusCode >= 500) {
uni.showToast({ title: '服务器繁忙,请稍后重试', icon: 'none' })
reject(new Error('服务器错误'))
return
}
const body = res.data
// 业务逻辑判断根据success字段
if (body && body.success) {
resolve(body)
} else {
const msg = (body && body.message) || '请求失败'
uni.showToast({ title: msg, icon: 'none' })
reject(new Error(msg))
}
},
fail: (err) => {
// 网络错误(超时、断网等)
const msg = err.errMsg || ''
if (msg.includes('timeout')) {
uni.showToast({ title: '网络连接超时,请重试', icon: 'none' })
} else {
uni.showToast({ title: '网络连接失败,请检查网络设置', icon: 'none' })
}
reject(new Error(msg || '网络错误'))
}
})
})
}
/**
* 发起GET请求
* @param {string} url - 请求路径
* @param {object} params - 查询参数
* @returns {Promise<{success: boolean, data: any, message: string}>}
*/
export function get(url, params) {
return request(url, { method: 'GET', data: params })
}
/**
* 发起POST请求
* @param {string} url - 请求路径
* @param {object} data - 请求体
* @returns {Promise<{success: boolean, data: any, message: string}>}
*/
export function post(url, data) {
return request(url, { method: 'POST', data })
}
/**
* 发起DELETE请求
* @param {string} url - 请求路径
* @returns {Promise<{success: boolean, data: any, message: string}>}
*/
export function del(url) {
return request(url, { method: 'DELETE' })
}