From 906ef15e4b4e50a341c77f8bb228e118bf468df4 Mon Sep 17 00:00:00 2001 From: mileswa1q22 Date: Tue, 31 Mar 2026 18:47:49 -0500 Subject: [PATCH] Use live server endpoints; add CORS/basePath Point the client to a configurable live server (live API, events and data file) and accept both JSON and plain-text list formats. Update app.js to parse JSON or text responses, use live EventSource and PUT endpoints, and fall back to the live data file when needed. On the server side, add BASE_PATH support (trim trailing slash) and normalize request paths so the app can be mounted under a subpath. Add setCorsHeaders and enable CORS (including handling OPTIONS preflight) for API, events and file responses, return proper headers on errors, and log the base path at startup. These changes enable cross-origin access and deployment under a base path while improving robustness of list parsing. --- app.js | 22 +++++++++++++++------- server/server.js | 31 +++++++++++++++++++++++++++---- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/app.js b/app.js index 632b71f..24c31a0 100644 --- a/app.js +++ b/app.js @@ -3,6 +3,10 @@ function qs(id){return document.getElementById(id)} const page = document.body.dataset.page; + const liveServerBase = 'https://raspberrypi-1.tail46eacb.ts.net/fedl'; + const liveApiUrl = `${liveServerBase}/api/list`; + const liveEventsUrl = `${liveServerBase}/events`; + const liveDataFileUrl = `${liveServerBase}/server/data.txt`; let cachedItems = null; let cachedLevelMeta = null; let liveBound = false; @@ -48,14 +52,18 @@ function loadItems(){ if(cachedItems) return Promise.resolve(cachedItems); - return fetch('/api/list', {cache:'no-store'}).then(r=>{ + return fetch(liveApiUrl, {cache:'no-store'}).then(r=>{ if(!r.ok) throw new Error('API unavailable'); - return r.json(); - }).then(data=>{ - cachedItems = Array.isArray(data.items) ? data.items : []; + const contentType = (r.headers.get('content-type') || '').toLowerCase(); + if(contentType.includes('application/json')){ + return r.json().then(data=>Array.isArray(data.items) ? data.items : []); + } + return r.text().then(txt=>parseData(txt)); + }).then(items=>{ + cachedItems = items; return cachedItems; }).catch(()=>{ - return fetch('server/data.txt', {cache:'no-store'}).then(r=>{ + return fetch(liveDataFileUrl, {cache:'no-store'}).then(r=>{ if(!r.ok) throw new Error('server data unavailable'); return r.text(); }).then(txt=>{ @@ -96,7 +104,7 @@ function bindLiveUpdates(){ if(liveBound || typeof window.EventSource === 'undefined') return; liveBound = true; - const source = new EventSource('/events'); + const source = new EventSource(liveEventsUrl); source.addEventListener('list-update', ()=>{ refreshItems().catch(err=>console.error(err)); }); @@ -440,7 +448,7 @@ })) .filter(item=>item.title); normalizePositions(); - return fetch('/api/list', { + return fetch(liveApiUrl, { method:'PUT', headers:{'Content-Type':'application/json'}, body: JSON.stringify({text: formatData(items)}) diff --git a/server/server.js b/server/server.js index faf0cf8..9195f8f 100644 --- a/server/server.js +++ b/server/server.js @@ -7,6 +7,7 @@ const appRoot = path.resolve(__dirname, '..'); const dataPath = path.join(__dirname, 'data.txt'); const port = Number(process.env.PORT) || 3000; const host = process.env.HOST || '127.0.0.1'; +const basePath = (process.env.BASE_PATH || '').replace(/\/$/, ''); const clients = new Set(); const contentTypes = { @@ -42,7 +43,14 @@ function readDataText() { return fs.readFileSync(dataPath, 'utf8'); } +function setCorsHeaders(res) { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,HEAD,OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); +} + function sendJson(res, statusCode, payload) { + setCorsHeaders(res); res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' @@ -69,11 +77,13 @@ function serveFile(reqPath, res) { fs.readFile(filePath, (err, data) => { if (err) { + setCorsHeaders(res); res.writeHead(err.code === 'ENOENT' ? 404 : 500, {'Content-Type': 'text/plain; charset=utf-8'}); res.end(err.code === 'ENOENT' ? 'Not found' : 'Server error'); return; } const ext = path.extname(filePath).toLowerCase(); + setCorsHeaders(res); res.writeHead(200, { 'Content-Type': contentTypes[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store' : 'no-cache' @@ -84,8 +94,18 @@ function serveFile(reqPath, res) { const server = http.createServer((req, res) => { const url = new URL(req.url, `http://${req.headers.host}`); + const pathname = basePath && url.pathname.startsWith(basePath) + ? url.pathname.slice(basePath.length) || '/' + : url.pathname; - if (req.method === 'GET' && url.pathname === '/api/list') { + if (req.method === 'OPTIONS') { + setCorsHeaders(res); + res.writeHead(204); + res.end(); + return; + } + + if (req.method === 'GET' && pathname === '/api/list') { try { const text = readDataText(); sendJson(res, 200, { items: parseData(text), text }); @@ -95,7 +115,7 @@ const server = http.createServer((req, res) => { return; } - if (req.method === 'PUT' && url.pathname === '/api/list') { + if (req.method === 'PUT' && pathname === '/api/list') { let body = ''; req.on('data', chunk => { body += chunk; @@ -117,7 +137,8 @@ const server = http.createServer((req, res) => { return; } - if (req.method === 'GET' && url.pathname === '/events') { + if (req.method === 'GET' && pathname === '/events') { + setCorsHeaders(res); res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache, no-transform', @@ -132,12 +153,13 @@ const server = http.createServer((req, res) => { } if (req.method !== 'GET' && req.method !== 'HEAD') { + setCorsHeaders(res); res.writeHead(405, {'Content-Type': 'text/plain; charset=utf-8'}); res.end('Method not allowed'); return; } - serveFile(url.pathname, res); + serveFile(pathname, res); }); fs.watch(dataPath, { persistent: true }, () => { @@ -147,4 +169,5 @@ fs.watch(dataPath, { persistent: true }, () => { server.listen(port, host, () => { console.log(`fedl server running at http://${host}:${port}`); console.log(`Using live list file: ${dataPath}`); + console.log(`Base path: ${basePath || '/'}`); });