-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (62 loc) · 1.77 KB
/
Copy pathindex.js
File metadata and controls
83 lines (62 loc) · 1.77 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// 1. Import express
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
// 2. Create an Express app
const app = express();
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
// 3. Define a route (when browser accesses "/")
app.get('/', async (req, res, next) => {
// res.send('Hello, World!').status(200);
// next();
try {
const filePath = path.join(__dirname, 'public', 'home.html');
const data = await fs.readFile(filePath, 'utf-8');
res.send(data);
} catch (error) {
console.error('Error reading file:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/about', (req, res) => {
res.send('This is the About page');
});
app.get('/contact', (req, res) => {
res.send('Contact us at: contact@example.com');
});
app.get('/welcome', (req, res) => {
res.send(`
<h1>Welcome to My Express App</h1>
<p>This is an HTML response.</p>
`);
});
app.post('/submit', async (req, res) => {
const userName = req.body.name;
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>submitted</title>
<link rel="stylesheet" href="static/css/styles.css">
</head>
<body>
<div class="container">
<h1>thanks ${userName}!</h1>
<p>thanks so much for filling the form!</p>
<p>courtesy of tobbi</p>
</div>
</body>
</html>
`);
});
// Optional: Handle not found
app.use((req, res) => {
res.status(404).send('Page not found');
});
// 4. Start the server on port 3000
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});