Files
counter/server/index.js
T
2026-11-14 17:16:57 +00:00

58 lines
1.6 KiB
JavaScript

'use strict';
const path = require('node:path');
const express = require('express');
const api = require('./router');
const app = express();
app.disable('x-powered-by');
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'same-origin');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
next();
});
app.use(express.json({ limit: '5mb' }));
app.use('/api', api);
// Serve the barcode scanner bundle from node_modules (no frontend build step).
app.use(
'/vendor/zxing',
express.static(path.join(__dirname, '..', 'node_modules', '@zxing', 'library', 'umd'), {
maxAge: '30d',
immutable: true,
})
);
app.use(
express.static(path.join(__dirname, '..', 'public'), {
maxAge: '10m',
setHeaders(res, filePath) {
if (filePath.endsWith('.html')) res.setHeader('Cache-Control', 'no-cache');
},
})
);
app.use((req, res, next) => {
if (req.method !== 'GET' && req.method !== 'HEAD') return next();
if (path.extname(req.path)) return next();
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.use((err, req, res, next) => {
const status = Number(err.status) >= 400 && Number(err.status) < 600 ? Number(err.status) : 500;
if (status >= 500) console.error(err);
res.status(status).json({ error: err.message || 'Unexpected error' });
});
const port = Number(process.env.PORT) || Number(process.env.APP_PORT) || 31490;
app.listen(port, '0.0.0.0', () => {
console.log(`Counter listening on http://0.0.0.0:${port} (data: ${process.env.DATA_DIR || './data'})`);
});