Skip to content

Instantly share code, notes, and snippets.

@Ovicakov
Created November 27, 2019 10:43
Show Gist options
  • Save Ovicakov/14c924010b9ad11efcebb7231652d4ce to your computer and use it in GitHub Desktop.
Save Ovicakov/14c924010b9ad11efcebb7231652d4ce to your computer and use it in GitHub Desktop.
Express4
const express = require('express');
const app = express();
const port = 3000;
const connection = require('./conf');
const bodyParser = require('body-parser');
// Support JSON-encoded bodies
app.use(bodyParser.json());
// Support URL-encoded bodies
app.use(bodyParser.urlencoded({
extended: true
}));
connection.connect(function (err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.get('/api/movies', (req, res) => {
connection.query('SELECT * FROM movie', (err, results) => {
if (err) {
res.status(500).send('Erreur de la récupération des films');
} else {
console.log(results);
res.json(results);
}
})
})
app.post('/api/movies', (req, res) => {
const formData = req.body
connection.query('INSERT INTO movie SET ?', formData, (err, res) => {
if (err) {
console.log(err);
res.status(500).send("Erreur lors de la sauvegarde d'un employé");
} else {
res.sendStatus(200);
console.log('prout');
}
});
});
app.get('/api/movies/names', (req, res) => {
connection.query('SELECT name FROM movie', (err, results) => {
if (err) {
res.status(500).send('Erreur de la récupération des noms');
} else {
console.log(results);
res.json(results);
}
})
})
app.put('/api/movies/:id', (req, res) => {
const idMovie = req.params.id;
const formData = req.body;
connection.query('UPDATE movie SET ? WHERE id = ?', [formData, idMovie], err => {
if (err) {
console.log(err);
res.status(500).send("Erreur lors de la modification d'un film");
} else {
res.sendStatus(200);
}
});
});
app.listen(port, (err) => {
if (err) {
throw new Error('Something bad happened...');
}
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