-
Notifications
You must be signed in to change notification settings - Fork 0
/
testapp.js
69 lines (57 loc) · 1.91 KB
/
testapp.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
64
65
66
67
68
69
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
app.use(express.static('public'));
app.set('view engine', 'ejs');
//middleware handle form data
app.use(bodyParser.urlencoded({ extended: true }));
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port} `);
console.log('Server running at http://localhost:3000/');
});
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
const customerName = null;
res.render('index', {title: 'Home', customerName: customerName});
});
app.get('/about', (req, res) => {
res.render('about', {title: 'About' });
});
app.get('/projects', (req, res) => {
res.render('projects', {title: 'Projects' });
});
app.get('/services', (req, res) => {
res.render('services', {title: 'Services' });
});
app.route('/contact')
.get((req, res) => {
res.render('contact', { title: 'Contact',service: req.query.service });
})
.post((req, res) => {
const { customerName, phoneNumber, email, service, comments } = req.body;
// Create a data object from the form input
const formData = {
customerName,
phoneNumber,
email,
service,
comments,
};
// Convert the form data to a JSON string
const formDataString = JSON.stringify(formData, null, 2);
// Define the path to the request.txt file
const filePath = path.join(__dirname, 'services', 'request.txt');
// Append the form data to the request.txt file
fs.appendFile(filePath, formDataString + '\n', (err) => {
if (err) {
console.error(err);
return res.redirect('/error'); // Handle errors gracefully
}
// Redirect to the confirmation page
res.render('index', {title: 'Home', customerName: customerName});
}); });