prima prova
This commit is contained in:
parent
4009b1a0be
commit
1a59bcf2b0
9 changed files with 1387 additions and 0 deletions
60
server.js
Normal file
60
server.js
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
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}`);
|
||||
});
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue