-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
64 lines (49 loc) · 1.55 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const express = require('express');
const fs = require('fs');
const app = express();
const port = 5501;
// Serve static files from the 'public' directory
app.use(express.static('.'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Route to handle form submission
app.post('/submit-form', (req, res) => {
console.log("Recevied a post request.")
const name = req.body.name;
const message = req.body.message;
const image = req.body.image;
// Save the data to a JSON file
const filePath = 'data.json';
const dataToSave = { name, message,image };
// Read the existing data
fs.readFile(filePath, (err, data) => {
// Initialize an empty array if the file doesn't exist or can't be read
let json = [];
if (!err) {
try {
json = JSON.parse(data);
} catch (parseErr) {
console.error('Error parsing JSON', parseErr);
res.status(500).send('An error occurred on the server.');
return;
}
}
json.push(dataToSave);
fs.writeFile(filePath, JSON.stringify(json, null, 2), (writeErr) => {
if (writeErr) {
console.error('Error writing to file', writeErr);
res.status(500).send('An error occurred on the server.');
return;
}
console.log('Data written to file');
res.json({success: true, message: 'Data written to file'})
});
});
});
// Start the server
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});