-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
76 lines (67 loc) · 2.14 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
64
65
66
67
68
69
70
71
72
73
74
75
76
const express = require('express');
const bodyParser = require('body-parser');
const db = require('./database');
const path = require('path');
const app = express();
const port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Trang chính: Hiển thị danh sách nhân viên
app.get('/', (req, res) => {
db.all('SELECT * FROM employees', [], (err, rows) => {
if (err) {
console.error(err.message);
res.status(500).send('Database error');
} else {
res.render('index', { employees: rows });
}
});
});
// Trang thêm nhân viên
app.get('/add', (req, res) => {
res.render('add');
});
app.post('/add', (req, res) => {
const { name, dob, position } = req.body;
db.run('INSERT INTO employees (name, dob, position) VALUES (?, ?, ?)', [name, dob, position], (err) => {
if (err) {
console.error(err.message);
res.status(500).send('Database error');
} else {
res.redirect('/');
}
});
});
// Xóa nhân viên
app.get('/delete/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM employees WHERE id = ?', [id], (err) => {
if (err) {
console.error(err.message);
res.status(500).send('Database error');
} else {
res.redirect('/');
}
});
});
// Tìm kiếm nhân viên
app.get('/search', (req, res) => {
res.render('search', { employees: null });
});
app.post('/search', (req, res) => {
const query = req.body.query;
db.all('SELECT * FROM employees WHERE name LIKE ?', [`%${query}%`], (err, rows) => {
if (err) {
console.error(err.message);
res.status(500).send('Database error');
} else {
res.render('search', { employees: rows });
}
});
});
// Bắt đầu server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});