AI-accounting-soft-uniApp/utils/request.js
2025-12-12 16:49:06 +08:00

186 lines
3.7 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.

// HTTP请求封装
const BASE_URL = process.env.NODE_ENV === 'development'
? 'http://localhost:8080/api'
: 'https://your-api-domain.com/api'
// 获取token
function getToken() {
return uni.getStorageSync('token') || ''
}
// 请求拦截器
function request(options) {
return new Promise((resolve, reject) => {
// 显示加载提示
if (options.loading !== false) {
uni.showLoading({
title: '加载中...',
mask: true
})
}
uni.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': options.contentType || 'application/json',
'Authorization': 'Bearer ' + getToken(),
...options.header
},
success: (res) => {
uni.hideLoading()
if (res.statusCode === 200) {
if (res.data.code === 200 || res.data.code === undefined) {
resolve(res.data)
} else {
// 业务错误
if (res.data.code === 401) {
// token过期跳转到登录页
uni.removeStorageSync('token')
uni.removeStorageSync('userInfo')
uni.reLaunch({
url: '/pages/login/login'
})
}
uni.showToast({
title: res.data.message || '请求失败',
icon: 'none'
})
reject(res.data)
}
} else if (res.statusCode === 401) {
// 未授权,跳转到登录页
uni.removeStorageSync('token')
uni.removeStorageSync('userInfo')
uni.reLaunch({
url: '/pages/login/login'
})
reject(res)
} else {
uni.showToast({
title: '请求失败',
icon: 'none'
})
reject(res)
}
},
fail: (err) => {
uni.hideLoading()
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 function upload(url, filePath, options = {}) {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '上传中...',
mask: true
})
uni.uploadFile({
url: BASE_URL + url,
filePath: filePath,
name: 'file',
header: {
'Authorization': 'Bearer ' + getToken()
},
formData: options.formData || {},
success: (res) => {
uni.hideLoading()
try {
const data = JSON.parse(res.data)
if (res.statusCode === 200) {
resolve(data)
} else {
uni.showToast({
title: data.message || '上传失败',
icon: 'none'
})
reject(data)
}
} catch (e) {
uni.showToast({
title: '上传失败',
icon: 'none'
})
reject(e)
}
},
fail: (err) => {
uni.hideLoading()
uni.showToast({
title: '上传失败',
icon: 'none'
})
reject(err)
}
})
})
}
export default {
get,
post,
put,
delete: del,
upload
}