Initialer Laravel Commit für BetiX
This commit is contained in:
16
resources/js/utils/api.ts
Normal file
16
resources/js/utils/api.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
// src/utils/api.ts
|
||||
import { ref } from 'vue';
|
||||
|
||||
// A reactive reference to hold the API URL.
|
||||
// It's initialized with a default/fallback value.
|
||||
export const apiUrl = ref('/api');
|
||||
|
||||
/**
|
||||
* Sets the global API URL from a reliable source, like the main layout component.
|
||||
* @param url The API base URL from Inertia props.
|
||||
*/
|
||||
export function initializeApiUrl(url: string | null | undefined) {
|
||||
if (url && typeof url === 'string') {
|
||||
apiUrl.value = url.replace(/\/$/, ''); // Remove trailing slash
|
||||
}
|
||||
}
|
||||
32
resources/js/utils/csrfFetch.ts
Normal file
32
resources/js/utils/csrfFetch.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
export type CsrfFetchOptions = RequestInit & { headers?: Record<string, any> };
|
||||
|
||||
function getMetaToken(): string | null {
|
||||
const el = document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null;
|
||||
return el?.content || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* fetch wrapper that automatically adds CSRF and common headers, and sends cookies.
|
||||
* - Uses local proxy to avoid Mixed Content (HTTPS -> HTTP) and CORS issues.
|
||||
* - Adds X-CSRF-TOKEN from <meta name="csrf-token"> if present
|
||||
* - Adds X-Requested-With: XMLHttpRequest for Laravel
|
||||
*/
|
||||
export async function csrfFetch(input: RequestInfo | URL, options: CsrfFetchOptions = {}): Promise<Response> {
|
||||
const token = getMetaToken();
|
||||
const headers: Record<string, any> = {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Accept': 'application/json',
|
||||
...(options.headers || {}),
|
||||
};
|
||||
if (token && !('X-CSRF-TOKEN' in headers)) {
|
||||
headers['X-CSRF-TOKEN'] = token;
|
||||
}
|
||||
|
||||
const init: RequestInit = {
|
||||
...options,
|
||||
headers,
|
||||
credentials: options.credentials ?? 'same-origin',
|
||||
};
|
||||
|
||||
return fetch(input, init);
|
||||
}
|
||||
Reference in New Issue
Block a user