const express = require('express'); const bodyParser = require('body-parser'); const fs = require('fs'); const path = require('path'); const app = express(); const PORT = 3000; // Middleware per servire file statici app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.json()); // Route per gestire gli ordini (POST) app.post('/ordini', (req, res) => { const { id_utente, tipo_pagamento, prodotti_acquistati, prezzo_totale, data } = req.body; const newOrder = { tipo_pagamento, prodotti_acquistati, prezzo_totale, data }; const filePath = path.join(__dirname, 'data', `${id_utente}.json`); // Crea la cartella "data" se non esiste if (!fs.existsSync('data')) { fs.mkdirSync('data'); } // Leggi gli ordini esistenti, se il file esiste let orders = []; if (fs.existsSync(filePath)) { const existingData = fs.readFileSync(filePath, 'utf8'); try { orders = JSON.parse(existingData); } catch (error) { console.error('Errore nel parsing del file JSON:', error); return res.status(500).send('Errore durante la lettura dell\'ordine esistente'); } } // Aggiungi il nuovo ordine agli ordini esistenti orders.push(newOrder); // Salva l'array aggiornato nel file fs.writeFile(filePath, JSON.stringify(orders, null, 2), (err) => { if (err) { console.error(err); return res.status(500).send('Errore durante il salvataggio dell\'ordine'); } res.status(200).send({ message: 'Ordine salvato' }); }); }); // Avvio del server app.listen(PORT, () => { console.log(`Server in esecuzione su http://localhost:${PORT}`); });