var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mysql = require('mysql'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // connection configurations var dbConn = mysql.createConnection({ host: 'localhost', port: 3306, user: 'nodeapiuser', password: 'RDSGF435FG', database: 'nodeapi' }); // connect to database dbConn.connect(); // Retrieve all users app.get('/users', function (req, res) { dbConn.query('SELECT * FROM users', function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results }); }); }); // Retrieve user with id app.get('/user/:id', function (req, res) { let user_id = req.params.id; if (!user_id) { return res.status(400).send({ error: true, message: 'Please provide user_id' }); } dbConn.query('SELECT * FROM users where id=?', user_id, function (error, results) { if (error) throw error; return res.send({ error: false, data: results[0] }); }); }); // Add a new user app.post('/user', function (req, res) { let nom = req.body.nom; let prenom = req.body.prenom; let email = req.body.email; console.log(nom, prenom, email); dbConn.query("INSERT INTO users (nom, prenom, email) VALUES (?,?,?);", [nom, prenom, email], function (error, results) { if (error) throw error; return res.send({ error: false, data: results, message: 'New user has been created successfully.' }); }); }); // Delete user app.delete('/user/:id', function (req, res) { let user_id = req.params.id; if (!user_id) { return res.status(400).send({ error: true, message: 'Please provide user_id' }); } dbConn.query('DELETE FROM users WHERE id = ?', [user_id], function (error, results, fields) { if (error) throw error; return res.send({ error: false, data: results, message: 'User has been deleted successfully.' }); }); }); // set port app.listen(8080, function () { console.log('Node app is running on port 8080'); }); module.exports = app;