49 lines
1.3 KiB
JavaScript
49 lines
1.3 KiB
JavaScript
// fastapi_url_manager/static/js/api.js
|
|
const API_BASE_URL = "/api";
|
|
|
|
async function makeApiRequest(method, path, data = null, requiresAuth = true) {
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (requiresAuth) {
|
|
const token = localStorage.getItem('access_token');
|
|
if (!token) {
|
|
console.error("No access token found. Redirecting to login.");
|
|
window.location.href = "/login"; // Redirect if token is missing
|
|
return null;
|
|
}
|
|
headers['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
|
|
const config = {
|
|
method: method,
|
|
headers: headers,
|
|
};
|
|
|
|
if (data) {
|
|
config.body = JSON.stringify(data);
|
|
}
|
|
|
|
const response = await fetch(`${API_BASE_URL}${path}`, config);
|
|
|
|
if (response.status === 401 || response.status === 403) {
|
|
console.error("Authentication failed or forbidden. Redirecting to login.");
|
|
localStorage.removeItem('access_token');
|
|
window.location.href = "/login";
|
|
return null;
|
|
}
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.detail || `API request failed with status ${response.status}`);
|
|
}
|
|
|
|
// For 204 No Content, return null
|
|
if (response.status === 204) {
|
|
return null;
|
|
}
|
|
|
|
return response.json();
|
|
}
|