Refactor API call to include CSRF token handling for non-GET requests

This commit is contained in:
2025-05-25 12:46:51 +02:00
parent ecc1fe9989
commit d2c4a84c32

View File

@@ -1,5 +1,22 @@
import { refreshToken } from './auth';
/**
* Gets the CSRF token from cookies
* @returns {string} The CSRF token or an empty string if not found
*/
const getCsrfToken = (): string => {
const cookies = document.cookie.split(';');
let csrfToken = '';
for (const cookie of cookies) {
const [name, value] = cookie.trim().split('=');
if (name === 'csrf_token' && value) {
csrfToken = decodeURIComponent(value);
break;
}
}
return csrfToken;
};
/**
* Makes an API call with proper cookie handling and error handling
*/
@@ -9,14 +26,26 @@ export const apiCall = async (
): Promise<Response> => {
console.debug(`Making API call to: ${url}`);
try {
// Set up headers with CSRF token for non-GET requests
const method = options.method || 'GET';
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
};
// Add CSRF token for non-GET methods
if (method !== 'GET') {
const csrfToken = getCsrfToken();
if (csrfToken) {
headers['X-CSRF-Token'] = csrfToken;
}
}
const response = await fetch(url, {
...options,
// Include credentials to send/receive cookies
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...options.headers,
},
headers,
});
console.debug(`Response status: ${response.status} for URL: ${url}`);