web / server.js
incognitolm
kghf
99df9a4
Raw
History Blame Contribute Delete
1.47 kB
const express = require('express');
const fs = require('fs');
const path = require('path');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const dataDir = path.join(__dirname, 'data');
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
const contactsFile = path.join(dataDir, 'contacts.json');
if (!fs.existsSync(contactsFile)) fs.writeFileSync(contactsFile, '[]');
app.get('/data/contacts', (req, res) => {
try {
const raw = fs.readFileSync(contactsFile, 'utf8');
const json = JSON.parse(raw || '[]');
res.json(json);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'failed to read contacts' });
}
});
app.post('/data/contacts', (req, res) => {
try {
const body = req.body || {};
const entry = {
name: body.name || '',
email: body.email || '',
subject: body.subject || '',
message: body.message || '',
createdAt: new Date().toISOString(),
};
const raw = fs.readFileSync(contactsFile, 'utf8');
const arr = JSON.parse(raw || '[]');
arr.unshift(entry);
fs.writeFileSync(contactsFile, JSON.stringify(arr, null, 2));
res.status(201).json(entry);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'failed to save contact' });
}
});
const port = process.env.PORT || 5173;
app.listen(port, () => console.log(`Data server listening on http://localhost:${port}`));