Last active
April 25, 2022 21:34
-
-
Save nicovray/c107b96d3a467718bf40834e3fd330fa to your computer and use it in GitHub Desktop.
Express 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const connection = require("./db-config"); | |
const express = require("express"); | |
const app = express(); | |
const port = process.env.PORT ?? 3000; | |
connection.connect((err) => { | |
if (err) { | |
console.error("error connecting: " + err.stack); | |
} else { | |
console.log("connected as id " + connection.threadId); | |
} | |
}); | |
app.use(express.json()); | |
app.get("/api/movies", (req, res) => { | |
connection.query("SELECT * FROM movies", (err, result) => { | |
if (err) { | |
console.error(err); | |
res.status(500).send("Error retrieving data from database"); | |
} else { | |
res.json(result); | |
} | |
}); | |
}); | |
app.post("/api/movies", (req, res) => { | |
const { title, director, year, color, duration } = req.body; | |
connection.query( | |
"INSERT INTO movies (title, director, year, color, duration) VALUES (?, ?, ?, ?, ?)", | |
[title, director, year, color, duration], | |
(err, result) => { | |
if (err) { | |
console.error(err); | |
res.status(500).send("Error saving the movie"); | |
} else { | |
res.status(200).send("Movie successfully saved"); | |
} | |
} | |
); | |
}); | |
app.post('/api/users',(req, res) => { | |
const {firstname, lastname, email} = req.body; | |
connection.query('INSERT INTO users(firstname, lastname, email) VALUES (?, ?, ?, ?)', [firstname, lastname, email]) | |
.then((result) =>{ | |
res.status(200).send('User successfully saved') | |
}).catch((err) => { | |
res.status(500).send('Error saving the user') | |
}) | |
}) | |
app.get("/api/users", (req, res) => { | |
connection.query("SELECT * FROM users", (err, result) => { | |
if (err) { | |
console.error(err); | |
res.status(500).send("Error retrieving data from database"); | |
} else { | |
res.json(result); | |
} | |
}); | |
}); | |
app.listen(port, (err) => { | |
if (err) { | |
console.error("Something bad happened"); | |
} else { | |
console.log(`Server is listening on ${port}`); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment