-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
89 lines (80 loc) · 2.75 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
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
84
85
86
87
88
89
const express = require("express");
const mysql = require("mysql");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
// Middleware
app.use(bodyParser.json());
app.use(cors());
// MySQL connection
const connection = mysql.createConnection({
host: "localhost",
user: "root", // ваш пользователь
password: "", // ваш пароль
database: "rew", // ваша база данных
});
connection.connect((err) => {
if (err) {
console.error("Error connecting to MySQL:", err);
return;
}
console.log("Connected to MySQL!");
});
// Routes
// Создание отзыва
app.post("/reviews", (req, res) => {
const { name, email, message } = req.body;
const INSERT_REVIEW_QUERY = `INSERT INTO reviews (name, email, message) VALUES (?, ?, ?)`;
connection.query(INSERT_REVIEW_QUERY, [name, email, message], (err, results) => {
if (err) {
console.error("Error creating review:", err);
res.status(500).send("Error creating review");
return;
}
res.status(201).send("Review created successfully");
});
});
// Получение всех отзывов
app.get("/reviews", (req, res) => {
const SELECT_REVIEWS_QUERY = `SELECT * FROM reviews`;
connection.query(SELECT_REVIEWS_QUERY, (err, results) => {
if (err) {
console.error("Error fetching reviews:", err);
res.status(500).send("Error fetching reviews");
return;
}
res.status(200).json(results);
});
});
// Обновление отзыва
app.put("/reviews/:id", (req, res) => {
const id = req.params.id;
const { name, email, message } = req.body;
const UPDATE_REVIEW_QUERY = `UPDATE reviews SET name = ?, email = ?, message = ? WHERE id = ?`;
connection.query(UPDATE_REVIEW_QUERY, [name, email, message, id], (err, results) => {
if (err) {
console.error("Error updating review:", err);
res.status(500).send("Error updating review");
return;
}
res.status(200).send("Review updated successfully");
});
});
// Удаление отзыва
app.delete("/reviews/:id", (req, res) => {
const id = req.params.id;
const DELETE_REVIEW_QUERY = `DELETE FROM reviews WHERE id = ?`;
connection.query(DELETE_REVIEW_QUERY, [id], (err, results) => {
if (err) {
console.error("Error deleting review:", err);
res.status(500).send("Error deleting review");
return;
}
res.status(200).send("Review deleted successfully");
});
});
// Start server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});