-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
48 lines (40 loc) · 1.16 KB
/
Copy pathserver.js
File metadata and controls
48 lines (40 loc) · 1.16 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
const express = require("express");
const dotenv = require("dotenv");
const mysql = require("mysql2");
const path = require("path");
// Load environment variables
dotenv.config(); // change path acc. (default: .env)
const app = express();
// Set the public directory for static files
app.use(express.static(path.join(__dirname, "public")));
// connect to db
const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
});
// Route to serve the HTML file
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
const tableName = process.env.TABLE_NAME;
app.get(`/${tableName}`, (req, res) => {
const query = `SELECT * FROM ${tableName}`;
db.query(query, (err, results) => {
if (err) {
return res.status(500).send("Database query failed.");
}
res.json(results);
});
});
// test connection
db.connect((err) => {
if (err) throw err;
console.log("Connected to database!");
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});