team-9/app/script.js
2025-08-01 23:41:32 +02:00

76 lines
No EOL
2.4 KiB
JavaScript

const API_BASE_URL = 'http://localhost:8000';
// Funzione per mostrare messaggi di status
function showStatus(message, isSuccess = true) {
const statusDiv = document.getElementById('status');
statusDiv.innerHTML = `<div class="status ${isSuccess ? 'success' : 'error'}">${message}</div>`;
}
// Funzione per mostrare i risultati
function showResult(data) {
const resultDiv = document.getElementById('result');
resultDiv.style.display = 'block';
resultDiv.textContent = JSON.stringify(data, null, 2);
}
// GET: Ottiene dati dal database
async function getData() {
try {
console.log('📥 Richiesta GET in corso...');
showStatus('📥 Richiesta GET in corso...', true);
const response = await fetch(`${API_BASE_URL}/api/data`);
const data = await response.json();
if (response.ok) {
showStatus('✅ Dati ottenuti con successo!', true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore GET:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// POST: Inserisce dati nel database
async function createData() {
try {
console.log('📤 Richiesta POST in corso...');
showStatus('📤 Richiesta POST in corso...', true);
const response = await fetch(`${API_BASE_URL}/api/data`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (response.ok) {
showStatus('✅ Dato inserito con successo!', true);
showResult(data);
} else {
showStatus(`❌ Errore: ${data.detail || 'Errore sconosciuto'}`, false);
}
} catch (error) {
console.error('Errore POST:', error);
showStatus(`❌ Errore di connessione: ${error.message}`, false);
}
}
// Test di connessione all'avvio
window.addEventListener('load', async () => {
try {
const response = await fetch(`${API_BASE_URL}/`);
if (response.ok) {
console.log('✅ Backend connesso!');
} else {
console.log('❌ Backend non raggiungibile');
}
} catch (error) {
console.log('❌ Backend non raggiungibile:', error.message);
}
});