42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
import {ref} from "vue";
|
|
|
|
export async function request(url, options = {}) {
|
|
const loading = ref(true)
|
|
const isFormData = options.body instanceof FormData
|
|
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
|
|
const data = ref(null)
|
|
const error = ref(null)
|
|
|
|
|
|
error.value = null
|
|
data.value = null
|
|
|
|
try {
|
|
const response = await fetch(url, {
|
|
method: options.method || "GET",
|
|
headers: {
|
|
'X-CSRF-TOKEN': csrfToken,
|
|
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
|
|
...(options.headers || {}),
|
|
},
|
|
body: isFormData
|
|
? options.body // ✅ FormData direkt
|
|
: options.body
|
|
? JSON.stringify(options.body)
|
|
: null,
|
|
})
|
|
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
|
|
const result = await response.json()
|
|
data.value = result
|
|
return result
|
|
} catch (err) {
|
|
error.value = err
|
|
console.error("AJAX Error:", err)
|
|
return null
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|