8.9 KiB
🔧 Guida: Come Cambiare il Path Base dell'Applicazione
Contesto
Il sistema Focolari Voting è composto da:
- Backend (FastAPI) che serve sia le API REST che il frontend statico
- Frontend (React SPA) che viene buildato e servito dal backend
Attualmente il frontend è servito su: /badge
📍 Configurazione Attuale
Backend serve su:
- API:
http://localhost:8000/api/info-room,/api/login-validate,/api/anagrafica/{badge},/api/entry-request - Frontend:
http://localhost:8000/badge - Debug page:
http://localhost:8000/badge/debug
Frontend in sviluppo:
- Vite dev server su
http://localhost:5173(qualsiasi base path) - Proxy
/api/*versohttp://127.0.0.1:8000
🔄 Come Cambiare il Path Base
Se in futuro vuoi servire il frontend su un path diverso (es. /votazioni, /app, / per la root), segui questi passaggi:
1️⃣ Backend - backend-mock/main.py
File: /backend-mock/main.py
Cerca le route del frontend (circa linea 94-114):
# Serve index.html su /badge e sue sub-route
@app.get("/badge")
async def serve_badge_index():
return FileResponse(STATIC_DIR / "index.html")
@app.get("/badge/debug")
async def serve_badge_debug():
return FileResponse(STATIC_DIR / "index.html")
# Monta i file statici (JS, CSS, assets) sotto /badge
app.mount("/badge/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")
# Fallback per altri file statici sotto /badge
@app.get("/badge/{filename:path}")
async def serve_static(filename: str):
# ...
Modifica necessaria:
- Sostituisci
/badgecon il nuovo path desiderato in TUTTE le occorrenze - Esempio per
/votazioni:@app.get("/votazioni") @app.get("/votazioni/debug") app.mount("/votazioni/assets", ...) @app.get("/votazioni/{filename:path}")
Cerca anche il messaggio di avvio (circa linea 177):
print(f"🌐 Frontend disponibile su http://{args.host}:{args.port}/badge")
Cambia in:
print(f"🌐 Frontend disponibile su http://{args.host}:{args.port}/NUOVO_PATH")
2️⃣ Frontend - frontend/src/main.tsx
File: /frontend/src/main.tsx
Cerca il BrowserRouter (circa linea 12):
<BrowserRouter basename="/badge">
Modifica necessaria:
- Cambia
basename="/badge"con il nuovo path - Esempio:
basename="/votazioni"oppurebasename="/"per la root
Cerca anche il callback onBack (circa linea 8):
return <DebugScreen onBack={() => window.location.href = '/badge'}/>
Cambia in:
return <DebugScreen onBack={() => window.location.href = '/NUOVO_PATH'}/>
3️⃣ Frontend - frontend/vite.config.ts
File: /frontend/vite.config.ts
Cerca la configurazione proxy (circa linea 32):
// Proxy API in sviluppo verso il backend (porta 8000)
// In produzione il backend serve il frontend su /badge e le API su /api/*
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
},
},
Modifica necessaria (solo se cambi il path delle API):
- Se le API cambiano da
/api/*a un altro path, aggiorna qui - Normalmente NON è necessario cambiare questo
Aggiorna anche il commento per riflettere il nuovo path frontend (solo documentazione).
4️⃣ Come Cambiare il Path delle API (Opzionale)
⚠️ Attenzione: Questo è separato dal path del frontend!
Attualmente le API sono su /api/*. Se vuoi cambiarle (es. /v1/* o /rest/*):
Backend - backend-mock/api/routes.py:
# Cerca tutte le route decorator (4 endpoint)
@router.get("/api/info-room", ...) # → @router.get("/v1/info-room", ...)
@router.post("/api/login-validate", ...) # → @router.post("/v1/login-validate", ...)
@router.get("/api/anagrafica/{badge_code}", ...) # → @router.get("/v1/anagrafica/{badge_code}", ...)
@router.post("/api/entry-request", ...) # → @router.post("/v1/entry-request", ...)
Frontend - frontend/src/services/api.ts:
// Cerca tutte le chiamate API (4 endpoint)
return apiFetch<RoomInfo>('/api/info-room'); // → '/v1/info-room'
return apiFetch<LoginResponse>('/api/login-validate', ...); // → '/v1/login-validate'
return apiFetch<User>(`/api/anagrafica/${...}`); // → `/v1/anagrafica/${...}`
return apiFetch<EntryResponse>('/api/entry-request', ...); // → '/v1/entry-request'
Frontend - frontend/vite.config.ts:
proxy: {
'/api': { // → '/v1': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
},
📝 Caso Speciale: Root Path /
Se vuoi servire il frontend direttamente sulla root (http://localhost:8000/):
Backend:
@app.get("/")
async def serve_index():
return FileResponse(STATIC_DIR / "index.html")
@app.get("/debug")
async def serve_debug():
return FileResponse(STATIC_DIR / "index.html")
app.mount("/assets", StaticFiles(directory=STATIC_DIR / "assets"), name="assets")
@app.get("/{filename:path}")
async def serve_static(filename: str):
# ... fallback logic
Frontend:
<BrowserRouter basename="/">
// oppure semplicemente:
<BrowserRouter>
⚠️ Attenzione: Se usi la root, le API REST devono essere montate PRIMA del catch-all /{filename:path}, altrimenti verranno intercettate dal frontend.
✅ Checklist Completa
Per Cambiare il Path del Frontend (es. /badge → /votazioni):
- Backend: Modifica tutte le route
@app.get("/badge...")→@app.get("/NUOVO_PATH...") - Backend: Modifica
app.mount("/badge/assets", ...)→app.mount("/NUOVO_PATH/assets", ...) - Backend: Aggiorna il messaggio di avvio con il nuovo URL
- Frontend: Aggiorna
basename="/badge"inmain.tsx - Frontend: Aggiorna il link di ritorno in
DebugWrapper - Frontend: (Opzionale) Aggiorna i commenti in
vite.config.ts - Test: Rebuild del frontend con
./dev.sh build - Test: Avvio del server con
./dev.sh server - Test: Verifica che
http://localhost:8000/NUOVO_PATHfunzioni - Test: Verifica che
http://localhost:8000/NUOVO_PATH/debugfunzioni - Test: Verifica che le API continuino a funzionare (servite su
/api/*)
Per Cambiare il Path delle API (es. /api/* → /v1/*):
- Backend: Modifica tutti i
@router.get("/api/...")inapi/routes.py - Frontend: Modifica tutte le chiamate
apiFetch('/api/...')inservices/api.ts - Frontend: Aggiorna il proxy in
vite.config.ts - Frontend: Aggiorna
baseURLinplaywright.config.tsse usi test E2E - Test: Verifica che tutte le API rispondano sul nuovo path
- Test: Test E2E (
./dev.sh test:e2e) per verificare integrazione completa
🔬 Test dopo il Cambio
# 1. Pulisci e rebuilda
./dev.sh clean
./dev.sh build
# 2. Avvia il server completo
./dev.sh server
# 3. Testa nel browser
# - http://localhost:8000/NUOVO_PATH
# - http://localhost:8000/NUOVO_PATH/debug
# - http://localhost:8000/docs (API docs, deve rimanere fuori dal path frontend)
# 4. Test API dirette (servite su /api/*)
curl http://localhost:8000/api/info-room
curl http://localhost:8000/api/anagrafica/0008988288
🎯 Files da Modificare - Riepilogo
Cambio Path Frontend (/badge → altro):
| File | Cosa Modificare | Linee Circa |
|---|---|---|
backend-mock/main.py |
Route @app.get("/badge") e varianti |
~94-114 |
backend-mock/main.py |
Messaggio avvio print(...) |
~177 |
frontend/src/main.tsx |
basename="/badge" in BrowserRouter |
~12 |
frontend/src/main.tsx |
window.location.href = '/badge' |
~8 |
frontend/vite.config.ts |
Commento documentazione (opzionale) | ~32 |
Cambio Path API (/api/* → altro):
| File | Cosa Modificare | Linee Circa |
|---|---|---|
backend-mock/api/routes.py |
Tutti i @router.get("/api/...") (4 route) |
~58, 67, 96, 118 |
frontend/src/services/api.ts |
Tutte le chiamate apiFetch('/api/...') (4 chiamate) |
~95, 108, 120, 135 |
frontend/vite.config.ts |
Proxy '/api' |
~35 |
💡 Nota Importante
Il sistema usa due path separati:
-
Frontend SPA (React): servito su
/badgehttp://localhost:8000/badge→ App principalehttp://localhost:8000/badge/debug→ Pagina debughttp://localhost:8000/badge/assets/*→ File statici (JS, CSS, immagini)
-
API REST (FastAPI): servite su
/api/*http://localhost:8000/api/info-roomhttp://localhost:8000/api/login-validatehttp://localhost:8000/api/anagrafica/{badge}http://localhost:8000/api/entry-request
Questi due path sono indipendenti e possono essere cambiati separatamente.
Vantaggio: Le API sono sempre accessibili su un path fisso, anche se il frontend cambia posizione.
Documento creato: 2026-02-04