Files
zkxw/mobile-oa-h5/src/utils/http.js
T

51 lines
1.5 KiB
JavaScript

import { getToken } from './auth.js'
const API_BASE = (import.meta.env.VITE_API_BASE || '/api').replace(/\/$/, '')
function unwrap(body) {
if (body == null || typeof body !== 'object') {
throw new Error('网络异常,请稍后重试')
}
if (body.code === 200) return body.data
throw new Error((body.message && String(body.message).trim()) || '请求失败')
}
export async function request({ url, method = 'GET', data, headers = {} }) {
const path = url.startsWith('/') ? url : `/${url}`
const full = `${API_BASE}${path}`
const token = getToken()
const init = {
method: method.toUpperCase(),
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...headers
}
}
if (data instanceof FormData) {
init.body = data
} else if (data != null && init.method !== 'GET') {
init.headers['Content-Type'] = 'application/json'
init.body = JSON.stringify(data)
}
let finalUrl = full
if (init.method === 'GET' && data && typeof data === 'object') {
const q = new URLSearchParams()
Object.entries(data).forEach(([k, v]) => {
if (v != null && v !== '') q.set(k, String(v))
})
const s = q.toString()
if (s) finalUrl += (finalUrl.includes('?') ? '&' : '?') + s
}
const res = await fetch(finalUrl, init)
const body = await res.json().catch(() => null)
return unwrap(body)
}
export function get(url, params) {
return request({ url, method: 'GET', data: params })
}
export function post(url, data) {
return request({ url, method: 'POST', data })
}