forked from Avdhesh-Varshney/WebMasterLog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
49 lines (42 loc) · 1.32 KB
/
server.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
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const db = require('./db/config');
const app = express();
const PORT = 3000;
// Middleware
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/api/items', (req, res) => {
db.query('SELECT * FROM items', (err, results) => {
if (err) throw err;
res.json(results);
});
});
app.post('/api/items', (req, res) => {
const { name, description } = req.body;
db.query('INSERT INTO items (name, description) VALUES (?, ?)', [name, description], (err, results) => {
if (err) throw err;
res.json({ id: results.insertId, name, description });
});
});
app.put('/api/items/:id', (req, res) => {
const { id } = req.params;
const { name, description } = req.body;
db.query('UPDATE items SET name = ?, description = ? WHERE id = ?', [name, description, id], (err) => {
if (err) throw err;
res.json({ id, name, description });
});
});
app.delete('/api/items/:id', (req, res) => {
const { id } = req.params;
db.query('DELETE FROM items WHERE id = ?', [id], (err) => {
if (err) throw err;
res.json({ message: 'Item deleted' });
});
});
// Start Server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});