odf_new/odf-uniapp/services/api.js
zpc cdc4a78198
Some checks reported errors
continuous-integration/drone/push Build encountered an error
1.2.0
2026-04-20 14:20:30 +08:00

92 lines
2.2 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.

// services/api.js
import store from '@/store'
// 默认值(兜底,实际会被 config.json 覆盖)
let BASE_URL = 'https://api.wux.shhmkjgs.cn'
export const APP_VERSION = '1.0.5'
const TIMEOUT = 20000
/**
* 从 static/config.json 加载运行时配置(仅 H5 生效)
* H5 部署时通过 docker volume 挂载替换 config.json 即可换环境
* App/小程序直接用打包时的默认值
*/
export function loadConfig() {
return new Promise((resolve) => {
// #ifdef H5
fetch('/static/config.json?t=' + Date.now())
.then(res => res.json())
.then(config => {
if (config.BASE_URL) BASE_URL = config.BASE_URL
console.log('[config] loaded BASE_URL:', BASE_URL)
resolve()
})
.catch(err => {
console.warn('[config] load failed, using default:', err)
resolve()
})
// #endif
// #ifndef H5
resolve()
// #endif
})
}
/**
* 获取当前 BASE_URL供外部拼接图片等地址使用
*/
export function getBaseUrl() {
return BASE_URL
}
/**
* 统一请求封装
* @param {string} method - GET | POST
* @param {string} url - 接口路径
* @param {object} data - 请求参数
* @param {object} options - 额外选项 { timeout }
* @returns {Promise<{code, msg, data}>}
*/
export function request(method, url, data = {}, options = {}) {
return new Promise((resolve, reject) => {
const header = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${store.token}`,
'Userid': store.userId,
'Username': store.userName
}
uni.request({
url: BASE_URL + url,
method,
data: method === 'GET' ? undefined : data,
// GET 参数通过 data 字段传递UniApp 会自动拼接为 queryString
...(method === 'GET' ? {
data
} : {}),
header,
timeout: options.timeout || TIMEOUT,
success(res) {
const {
code,
msg,
data: resData
} = res.data
resolve({
code,
msg,
data: resData
})
},
fail(err) {
reject({
code: -1,
msg: err.errMsg || '网络异常'
})
}
})
})
}
export const get = (url, params, options) => request('GET', url, params, options)
export const post = (url, data, options) => request('POST', url, data, options)