Skip to content

Instantly share code, notes, and snippets.

@chaiwa-berian
Created June 28, 2019 20:35
Show Gist options
  • Save chaiwa-berian/e9008b605c36057c5f77f4867f12cdb7 to your computer and use it in GitHub Desktop.
Save chaiwa-berian/e9008b605c36057c5f77f4867f12cdb7 to your computer and use it in GitHub Desktop.
MVC+Express+MySQL+NodeJs
module.exports = function(app, connection){
//Routing requests for /books
app.use('/books', require('./books.router')(connection));
//List any other potential routes below
}
let BookModel = require('../models/books_model');
//GET /books
async function getAllBooks(req, res, next) {
try {
await BookModel.query("select * from books", function (error,results, fields) {
if (error) throw error;
res.status(200).send(results);
return;
});
} catch (error) {
console.log(error);
return next(error);
}
};
let router = require('express').Router();
let controller = require('../controllers/books_controller');
//If a request comes like GET /books, this is the endpoint
router.route('/')
.get(controller.getAllBooks);
module.exports = router;
const express = require('express');
const app = express();
const mysql = require('mysql') //assuming you installed mysql( npm install mysql --save)
//Connect to the database
let connection = mysql.createConnection({
debug:true,
host:'localhost',
user:'user',
password:'password',
database:'database'
});
connection.connect(function(error){
if(!!error){
console.log(error);
}else{
console.log('Connected!:)');
}
});
//Load Routes
require('../routes/app_router')(app, connection); //this will be the first-level/app-level router responsible for loading specific endpoint routers
//Setup server
const PORT = 3000;
let server = app.listen(PORT, function(){
console.log('Server listening on port ', PORT);
});
module.exports = server;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment