Fix Nginx y Boostrap

This commit is contained in:
2025-09-03 14:05:06 -03:00
parent a81f1fe894
commit 36a004a0b0
2 changed files with 37 additions and 25 deletions

View File

@@ -1,8 +1,9 @@
// public/bootstrap.js
(function() { (function() {
// --- CONFIGURACIÓN --- // --- LÓGICA DE DETECCIÓN AUTOMÁTICA DE LA RUTA BASE ---
// Cambie esto por el dominio final en producción // document.currentScript.src nos da la URL completa del propio script bootstrap.js
const WIDGETS_HOST = 'https://elecciones2025.eldia.com'; const scriptUrl = new URL(document.currentScript.src);
// La ruta base es el origen (ej. 'https://elecciones2025.eldia.com')
const WIDGETS_HOST = scriptUrl.origin;
// --- FUNCIONES AUXILIARES (sin cambios) --- // --- FUNCIONES AUXILIARES (sin cambios) ---
function loadScript(src) { function loadScript(src) {
@@ -26,21 +27,23 @@
// --- LÓGICA PRINCIPAL --- // --- LÓGICA PRINCIPAL ---
async function initWidgets() { async function initWidgets() {
try { try {
// 1. Obtener el manifest.json // 1. Obtener el manifest.json desde la ruta base detectada
const response = await fetch(`${WIDGETS_HOST}/manifest.json`); const response = await fetch(`${WIDGETS_HOST}/manifest.json`);
if (!response.ok) throw new Error('No se pudo cargar el manifest.'); if (!response.ok) {
throw new Error('No se pudo cargar el manifest de los widgets. (404 Not Found)');
}
const manifest = await response.json(); const manifest = await response.json();
// 2. Encontrar el punto de entrada principal (nuestro main.tsx) // 2. Encontrar el punto de entrada principal
// En modo 'lib', la entrada es el propio archivo de entrada. const entryKey = Object.keys(manifest).find(key => manifest[key].isEntry);
const entryKey = 'src/main.tsx'; if (!entryKey) {
const entry = manifest[entryKey]; throw new Error('No se encontró el punto de entrada en el manifest.');
}
if (!entry) throw new Error('No se encontró el punto de entrada en el manifest.');
const entry = manifest[entryKey];
const jsUrl = `${WIDGETS_HOST}/${entry.file}`; const jsUrl = `${WIDGETS_HOST}/${entry.file}`;
// 3. Cargar el CSS asociado, si existe // 3. Cargar el CSS
if (entry.css && entry.css.length > 0) { if (entry.css && entry.css.length > 0) {
entry.css.forEach(cssFile => { entry.css.forEach(cssFile => {
const cssUrl = `${WIDGETS_HOST}/${cssFile}`; const cssUrl = `${WIDGETS_HOST}/${cssFile}`;
@@ -48,14 +51,13 @@
}); });
} }
// 4. Cargar el script principal de la librería // 4. Cargar el JS principal
await loadScript(jsUrl); await loadScript(jsUrl);
// 5. Esperar a que la página esté completamente cargada // 5. El addEventListener ya no es necesario aquí, el consumidor lo añade.
// y luego llamar a la función de renderizado. // Si quiere que sea totalmente automático, puede añadirlo:
window.addEventListener('load', function () { window.addEventListener('load', function () {
if (window.EleccionesWidgets && typeof window.EleccionesWidgets.render === 'function') { if (window.EleccionesWidgets && typeof window.EleccionesWidgets.render === 'function') {
console.log('Elecciones Widgets listos. Renderizando...');
window.EleccionesWidgets.render(); window.EleccionesWidgets.render();
} }
}); });
@@ -65,7 +67,6 @@
} }
} }
// Iniciar el proceso
initWidgets(); initWidgets();
})(); })();

View File

@@ -1,5 +1,17 @@
# ./proxy/nginx.conf # ./proxy/nginx.conf
# --- MAPA DE ORÍGENES PERMITIDOS ---
# Este bloque debe estar fuera de los bloques 'server'.
# Comprueba la cabecera 'Origin' de la petición ($http_origin) y, si coincide,
# establece la variable $cors_origin con ese valor. Si no, queda vacía.
map $http_origin $cors_origin {
default '';
'https://www.eldia.com' $http_origin;
'https://extras.eldia.com' $http_origin;
'http://localhost:5173' $http_origin; # Para desarrollo local
# Añada aquí cualquier otro dominio de desarrollo si es necesario
}
# --- Upstreams (Definiciones de nuestros servicios) --- # --- Upstreams (Definiciones de nuestros servicios) ---
upstream backend_api { upstream backend_api {
server elecciones-api:8080; server elecciones-api:8080;
@@ -26,13 +38,12 @@ server {
# --- RUTA PARA EL FRONTEND PÚBLICO --- # --- RUTA PARA EL FRONTEND PÚBLICO ---
location / { location / {
# ¡CRUCIAL! Permite que los widgets se incrusten en otros sitios. # Añadimos la cabecera usando la variable que definimos en el mapa.
# Esto es más seguro que un '*' genérico. add_header 'Access-Control-Allow-Origin' $cors_origin always;
add_header 'Access-Control-Allow-Origin' 'https://www.eldia.com, https://extras.eldia.com, http://localhost:5173' always; add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
if ($request_method = 'OPTIONS') { if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
return 204; return 204;
} }