You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
import store from '../store';import config from '@/utils/config.js'const BASE_URL = config.baseUrl
// 把对象转 queryString,数组展开为 key=val&key=val
function buildQuery(params) { const parts = [] for (const key in params) { const val = params[key] if (val === null || val === undefined) continue if (Array.isArray(val)) { // 数组:多次追加 key=xxx
val.forEach(item => { parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(item)}`) }) } else { parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(val)}`) } } return parts.join('&')}
function request({ url, data, method = 'GET' }) { return new Promise((resolve, reject) => { // 自动带上 token
const header = {}; if (store.state.user.token) { header.Authorization = store.state.user.token; }
let finalUrl = BASE_URL + url let finalData = data
// GET 请求:手动拼装query,数组展开多同名参数
if (method.toUpperCase() === 'GET' && data && typeof data === 'object') { const query = buildQuery(data) if (query) { finalUrl += (finalUrl.includes('?') ? '&' : '?') + query } finalData = undefined // GET 清空data,防止uni.request重复处理
}
uni.request({ url: finalUrl, data: finalData, method: method.toUpperCase(), header, success: ({ data }) => { if (data.code === 200) { resolve(data); } else { uni.showToast({ title: data.message || '请求失败', icon: 'none', mask: true, duration: 3000 }); reject(data.message); } }, fail: (error) => { uni.showToast({ title: '网络异常', icon: 'none' }); reject(error); }, complete: () => { uni.hideLoading(); } }); });}
export default request;
|