Files
todo-frontend/src/api/index.js
Agent 80b6fa0fe5
All checks were successful
continuous-integration/drone/push Build is passing
fix: 登录后保存role,API请求携带X-User-Role头
2026-03-29 08:42:02 +00:00

59 lines
1.7 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.
// API基础配置
const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'https://sales.violin-work.online/api/v1'
// 请求拦截器
const request = (url, method, query = {}, data = {}) => {
const token = uni.getStorageSync('token')
const userId = uni.getStorageSync('userId') || ''
const username = uni.getStorageSync('username') || ''
const role = uni.getStorageSync('role') || ''
// 特殊情况:入库和库存调整需要 form-urlencoded 格式
const useFormData = (url.includes('/stock/in') || url.includes('/stock/adjust')) && Object.keys(data).length > 0
// GET 请求用 query 参数,其他请求有 data 时发 data没 data 时发空对象
let requestData = {}
if (method === 'GET') {
requestData = query
} else if (Object.keys(data).length > 0) {
requestData = data
}
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + url,
method: method,
data: requestData,
header: {
'Content-Type': useFormData ? 'application/x-www-form-urlencoded' : 'application/json',
'Authorization': token ? `Bearer ${token}` : '',
'X-User-Id': userId,
'X-Username': username,
'X-User-Role': role
},
success: (res) => {
if (res.data.code === 0) {
resolve(res.data.data)
} else {
uni.showToast({
title: res.data.message || '请求失败',
icon: 'none'
})
reject(res.data)
}
},
fail: (err) => {
uni.showToast({
title: '网络请求失败',
icon: 'none'
})
reject(err)
}
})
})
}
export default {
request
}