· 6 years ago · Mar 27, 2020, 04:46 PM
1const express = require('express');
2const bodyParser = require('body-parser');
3const path = require('path');
4const mysql = require('mysql');
5const cors = require('cors');
6
7const PORT = process.env.PORT || 8080;
8const app = express();
9
10//STATIC FOLDER
11app.use(express.static(path.join(__dirname, '../client/build')));
12
13//URLEncoded
14app.use(bodyParser.urlencoded({extended: true}));
15
16// Body Parser Middleware
17app.use(bodyParser.json());
18
19// Deal with CORS
20app.use(cors());
21
22//CREATE CONNECTION
23// @see documentenation at https://github.com/mysqljs/mysql
24const db = mysql.createConnection({
25 host: process.env.DB_HOST,
26 user: process.env.DB_USER,
27 password: process.env.DB_PASSWORD,
28 database: process.env.DB_DATABASE
29});
30
31//CONNECT
32db.connect((err) => {
33 if (err) throw err;
34 console.log('MySQL Connected...');
35});
36
37function queryDB() {
38 //create database
39 db.query("CREATE TABLE `jstest`.`new_table` (\n" +
40 " `id` INT NOT NULL,\n" +
41 " `first-name` VARCHAR(45) NULL,\n" +
42 " `lasat-name` VARCHAR(45) NULL,\n" +
43 " PRIMARY KEY (`id`));\n")
44}
45
46
47// Start Express listening
48app.listen(PORT, () => {
49 console.log(`Server started on port ${PORT}`);
50});
51
52// Test
53
54// Test to make sure the API can talk to React
55app.get('/', (req, res) => {
56 return res.json({
57 status: res.statusCode,
58 data: {
59 message: 'API Active'
60 }
61 });
62});
63
64// An echo, to help with debugging
65app.post('/', (req, res) => {
66 queryDB(); //This line BREAKS everything to do with express
67 return res.json({
68 status: res.statusCode,
69 data: {
70 message: 'ECHO!',
71 posted: req.body
72 }
73 });
74});
75
76// An API endpoint to store form post data
77app.post('/create', (req, res) => {
78
79 //As does this
80 //Once any request, that includes code like this, is made it works properly ONCE or maybe TWICE before breaking.
81 db.query("CREATE TABLE `jstest`.`new_table` (\n" +
82 " `id` INT NOT NULL,\n" +
83 " `first-name` VARCHAR(45) NULL,\n" +
84 " `lasat-name` VARCHAR(45) NULL,\n" +
85 " PRIMARY KEY (`id`));\n")
86 return res.json({
87 status: res.statusCode,
88 data: {
89 message: 'Success',
90 }
91 });
92});