munch-ease-frontend/src/api/http.js

31 lines
992 B
JavaScript
Raw Normal View History

2025-10-18 01:30:30 +00:00
const BASE = process.env.VUE_APP_API_BASE || '/api'
async function request(path, options = {}) {
const url = path.startsWith('http') ? path : `${BASE}${path}`
const resp = await fetch(url, {
credentials: 'include',
...options,
headers: {
'Accept': 'application/json',
...(options.body ? { 'Content-Type': 'application/json' } : {}),
...(options.headers || {}),
},
})
if (!resp.ok) {
let message = `${resp.status} ${resp.statusText}`
try { const err = await resp.json(); message = err.message || message } catch (_) { /* ignore */ }
const error = new Error(message)
error.status = resp.status
throw error
}
if (resp.status === 204) return null
return resp.json()
}
export const http = {
get: (p) => request(p),
post: (p, body) => request(p, { method: 'POST', body: JSON.stringify(body) }),
put: (p, body) => request(p, { method: 'PUT', body: JSON.stringify(body) }),
del: (p) => request(p, { method: 'DELETE' }),
}