Created
August 18, 2018 20:02
-
-
Save coderdiaz/f39c707377058634ec0482dffc751ad5 to your computer and use it in GitHub Desktop.
Express API without best practices :v - Sprotify
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 mysql = require('mysql') | |
const express = require('express') | |
const app = express() | |
app.use(express.json()) | |
app.use(express.urlencoded({ extended: false })) | |
// Connection database | |
const connection = mysql.createConnection({ | |
host: '127.0.0.1', | |
user: 'root', | |
password: 'root', | |
database: 'mydb' | |
}) | |
// Routing | |
const router = express.Router(); | |
// GET / | |
router.get('/', (req, res) => { | |
return res.json({ | |
message: mensaje | |
}) | |
}) | |
connection.connect() | |
router.get('/artist', (req, res) => { | |
const whereCondition = (req.query.id) ? ` WHERE idartistas = ${req.query.id}` : '' | |
connection.query(`SELECT * FROM artistas ${whereCondition}`, (err, results, fields) => { | |
if (err) return res.json({ error: err }) | |
return res.json({ data: results }) | |
}) | |
}) | |
router.post('/artist', (req, res) => { | |
console.log(req) | |
connection.query(` | |
INSERT INTO artistas(nombre, debut, valoracion, bio) | |
VALUES( | |
"${req.body.nombre}", | |
"${req.body.debut}", | |
${req.body.valoracion}, | |
"${req.body.bio}" | |
) | |
`, (err, results, fields) => { | |
if (err) return res.json({ error: err }) | |
return res.json({ | |
message: 'Artist created!' | |
}); | |
}) | |
}); | |
app.use('/', router); | |
app.listen('8080'); | |
console.log('Listening on port 8080') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment