├── Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode ├── README.md ├── app │ ├── config │ │ ├── config.js │ │ ├── db.config.js │ │ └── env.js │ ├── controller │ │ └── controller.js │ ├── model │ │ ├── role.model.js │ │ └── user.model.js │ └── router │ │ ├── router.js │ │ ├── verifyJwtToken.js │ │ └── verifySignUp.js ├── package-lock.json ├── package.json └── server.js ├── Angular Nodejs Fullstack CRUD Application - Backend Development ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json ├── resources │ └── js │ │ ├── delete_customer.js │ │ ├── get_customer.js │ │ ├── post_customer.js │ │ └── update_customer.js ├── server.js └── view │ ├── customers.html │ └── index.html ├── Angular-10-Nodejs-MongoDB-Pagination ├── app │ ├── config │ │ └── mongodb.config.js │ ├── controllers │ │ └── customer.controller.js │ ├── models │ │ └── customer.model.js │ └── routes │ │ └── customer.router.js ├── package-lock.json ├── package.json └── server.js ├── Angular-Nodejs-Pagination - Backend Nodejs Development ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Angular-Nodejs-PostgreSQL-CRUD-Application-Backend ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Angular10-Nodejs-Express-MongoDB-CRUD-Example ├── app │ ├── config │ │ └── mongodb.config.js │ ├── controllers │ │ └── customer.controller.js │ ├── models │ │ └── customer.model.js │ └── routes │ │ └── customer.router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs Build CRUD Application ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json ├── resources │ └── js │ │ ├── delete_customer.js │ │ ├── get_customer.js │ │ ├── post_customer.js │ │ └── update_customer.js ├── server.js └── view │ ├── customers.html │ └── index.html ├── Nodejs RestAPIs Express Sequelize MySQL ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-Ajax-MySQL-Pagination-Examples ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json ├── resources │ └── js │ │ └── table.js ├── server.js └── view │ └── index.html ├── Nodejs-Express-MongoDB-CRUD-Example ├── app │ ├── config │ │ └── mongodb.config.js │ ├── controllers │ │ └── customer.controller.js │ ├── models │ │ └── customer.model.js │ └── routes │ │ └── customer.router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-MongoDB-Pagination-Example ├── app │ ├── config │ │ └── mongodb.config.js │ ├── controllers │ │ └── customer.controller.js │ ├── models │ │ └── customer.model.js │ └── routes │ │ └── customer.router.js ├── list-customers ├── package-lock.json ├── package.json └── server.js ├── Nodejs-Pagination-Filtering-Sorting ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-PostgreSQL-CRUD-Example ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-React-Integration-Example ├── README.md ├── package-lock.json ├── package.json └── server.js ├── Nodejs-Reactjs-MongoDB-CRUD-Example ├── README.md ├── app │ ├── config │ │ └── mongodb.config.js │ ├── controllers │ │ └── customer.controller.js │ ├── models │ │ └── customer.model.js │ └── routes │ │ └── customer.router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-Reactjs-MySQL-CRUD-Example ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-Reactjs-PostgreSQL-Example ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ └── env.js │ ├── controllers │ │ └── controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── router.js ├── package-lock.json ├── package.json └── server.js ├── Nodejs-Upload-CSV-Files ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ ├── env.js │ │ └── multer.config.js │ ├── controllers │ │ └── csv.controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── excel.router.js ├── package-lock.json ├── package.json ├── resources │ └── static │ │ └── js │ │ └── uploaddownloadfiles.js ├── server.js └── views │ └── index.html ├── Nodejs-Upload-Download-Files ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ ├── env.js │ │ └── multer.config.js │ ├── controllers │ │ └── file.controller.js │ ├── models │ │ └── file.model.js │ └── routers │ │ └── file.router.js ├── package-lock.json ├── package.json ├── resources │ └── static │ │ └── js │ │ └── uploaddownloadfiles.js ├── server.js └── views │ └── index.html ├── Nodejs-Upload-Excel-Files ├── README.md ├── app │ ├── config │ │ ├── db.config.js │ │ ├── env.js │ │ └── multer.config.js │ ├── controllers │ │ └── excel.controller.js │ ├── models │ │ └── customer.model.js │ └── routers │ │ └── excel.router.js ├── package-lock.json ├── package.json ├── resources │ └── static │ │ └── js │ │ └── uploaddownloadfiles.js ├── server.js └── views │ └── index.html ├── README.md └── Token Based Authentication in Nodejs using JWT(Json Web Token) Example ├── README.md ├── app ├── config │ ├── config.js │ ├── db.config.js │ └── env.js ├── controller │ └── controller.js ├── model │ ├── role.model.js │ └── user.model.js └── router │ ├── router.js │ ├── verifyJwtToken.js │ └── verifySignUp.js ├── package-lock.json ├── package.json └── server.js /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/README.md: -------------------------------------------------------------------------------- 1 | Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example - Express RestAPIs + JWT + BCryptjs + Sequelize 2 | https://loizenai.com/angular-10-nodejs-jwt-authentication-mysql-examples-tutorials/ 3 | -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/config/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'secret': 'loizenai-super-secret-key', 3 | ROLEs: ['USER', 'ADMIN', 'PM'] 4 | }; -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.user = require('../model/user.model.js')(sequelize, Sequelize); 23 | db.role = require('../model/role.model.js')(sequelize, Sequelize); 24 | 25 | db.role.belongsToMany(db.user, { through: 'user_roles', foreignKey: 'roleId', otherKey: 'userId'}); 26 | db.user.belongsToMany(db.role, { through: 'user_roles', foreignKey: 'userId', otherKey: 'roleId'}); 27 | 28 | module.exports = db; -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; 16 | -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/controller/controller.js: -------------------------------------------------------------------------------- 1 | const db = require('../config/db.config.js'); 2 | const config = require('../config/config.js'); 3 | const User = db.user; 4 | const Role = db.role; 5 | 6 | const Op = db.Sequelize.Op; 7 | 8 | var jwt = require('jsonwebtoken'); 9 | var bcrypt = require('bcryptjs'); 10 | 11 | exports.signup = (req, res) => { 12 | // Save User to Database 13 | console.log("Processing func -> SignUp"); 14 | 15 | User.create({ 16 | name: req.body.name, 17 | username: req.body.username, 18 | email: req.body.email, 19 | password: bcrypt.hashSync(req.body.password, 8) 20 | }).then(user => { 21 | Role.findAll({ 22 | where: { 23 | name: { 24 | [Op.or]: req.body.roles 25 | } 26 | } 27 | }).then(roles => { 28 | user.setRoles(roles).then(() => { 29 | res.send("User registered successfully!"); 30 | }); 31 | }).catch(err => { 32 | res.status(500).send("Error -> " + err); 33 | }); 34 | }).catch(err => { 35 | res.status(500).send("Fail! Error -> " + err); 36 | }) 37 | } 38 | 39 | exports.signin = (req, res) => { 40 | console.log("Sign-In"); 41 | 42 | User.findOne({ 43 | where: { 44 | username: req.body.username 45 | } 46 | }).then(user => { 47 | if (!user) { 48 | return res.status(404).send('User Not Found.'); 49 | } 50 | 51 | var passwordIsValid = bcrypt.compareSync(req.body.password, user.password); 52 | if (!passwordIsValid) { 53 | return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" }); 54 | } 55 | 56 | var token = jwt.sign({ id: user.id }, config.secret, { 57 | expiresIn: 86400 // expires in 24 hours 58 | }); 59 | 60 | res.status(200).send({ auth: true, accessToken: token }); 61 | 62 | }).catch(err => { 63 | res.status(500).send('Error -> ' + err); 64 | }); 65 | } 66 | 67 | exports.userContent = (req, res) => { 68 | User.findOne({ 69 | where: {id: req.userId}, 70 | attributes: ['name', 'username', 'email'], 71 | include: [{ 72 | model: Role, 73 | attributes: ['id', 'name'], 74 | through: { 75 | attributes: ['userId', 'roleId'], 76 | } 77 | }] 78 | }).then(user => { 79 | res.status(200).json({ 80 | "description": "User Content Page", 81 | "user": user 82 | }); 83 | }).catch(err => { 84 | res.status(500).json({ 85 | "description": "Can not access User Page", 86 | "error": err 87 | }); 88 | }) 89 | } 90 | 91 | exports.adminBoard = (req, res) => { 92 | User.findOne({ 93 | where: {id: req.userId}, 94 | attributes: ['name', 'username', 'email'], 95 | include: [{ 96 | model: Role, 97 | attributes: ['id', 'name'], 98 | through: { 99 | attributes: ['userId', 'roleId'], 100 | } 101 | }] 102 | }).then(user => { 103 | res.status(200).json({ 104 | "description": "Admin Board", 105 | "user": user 106 | }); 107 | }).catch(err => { 108 | res.status(500).json({ 109 | "description": "Can not access Admin Board", 110 | "error": err 111 | }); 112 | }) 113 | } 114 | 115 | exports.managementBoard = (req, res) => { 116 | User.findOne({ 117 | where: {id: req.userId}, 118 | attributes: ['name', 'username', 'email'], 119 | include: [{ 120 | model: Role, 121 | attributes: ['id', 'name'], 122 | through: { 123 | attributes: ['userId', 'roleId'], 124 | } 125 | }] 126 | }).then(user => { 127 | res.status(200).json({ 128 | "description": "Management Board", 129 | "user": user 130 | }); 131 | }).catch(err => { 132 | res.status(500).json({ 133 | "description": "Can not access Management Board", 134 | "error": err 135 | }); 136 | }) 137 | } -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/model/role.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Role = sequelize.define('roles', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | primaryKey: true 6 | }, 7 | name: { 8 | type: Sequelize.STRING 9 | } 10 | }); 11 | 12 | return Role; 13 | } -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/model/user.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const User = sequelize.define('users', { 3 | name: { 4 | type: Sequelize.STRING 5 | }, 6 | username: { 7 | type: Sequelize.STRING 8 | }, 9 | email: { 10 | type: Sequelize.STRING 11 | }, 12 | password: { 13 | type: Sequelize.STRING 14 | } 15 | }); 16 | 17 | return User; 18 | } -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/router/router.js: -------------------------------------------------------------------------------- 1 | const verifySignUp = require('./verifySignUp'); 2 | const authJwt = require('./verifyJwtToken'); 3 | 4 | module.exports = function(app) { 5 | 6 | const controller = require('../controller/controller.js'); 7 | 8 | app.post('/api/auth/signup', [verifySignUp.checkDuplicateUserNameOrEmail, verifySignUp.checkRolesExisted], controller.signup); 9 | 10 | app.post('/api/auth/signin', controller.signin); 11 | 12 | app.get('/api/test/user', [authJwt.verifyToken], controller.userContent); 13 | 14 | app.get('/api/test/pm', [authJwt.verifyToken, authJwt.isPmOrAdmin], controller.managementBoard); 15 | 16 | app.get('/api/test/admin', [authJwt.verifyToken, authJwt.isAdmin], controller.adminBoard); 17 | } -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/app/router/verifyJwtToken.js: -------------------------------------------------------------------------------- 1 | const jwt = require('jsonwebtoken'); 2 | const config = require('../config/config.js'); 3 | const db = require('../config/db.config.js'); 4 | const Role = db.role; 5 | const User = db.user; 6 | 7 | verifyToken = (req, res, next) => { 8 | let token = req.headers['x-access-token']; 9 | 10 | if (!token){ 11 | return res.status(403).send({ 12 | auth: false, message: 'No token provided.' 13 | }); 14 | } 15 | 16 | jwt.verify(token, config.secret, (err, decoded) => { 17 | if (err){ 18 | return res.status(500).send({ 19 | auth: false, 20 | message: 'Fail to Authentication. Error -> ' + err 21 | }); 22 | } 23 | req.userId = decoded.id; 24 | next(); 25 | }); 26 | } 27 | 28 | isAdmin = (req, res, next) => { 29 | let token = req.headers['x-access-token']; 30 | 31 | User.findByPk(req.userId) 32 | .then(user => { 33 | user.getRoles().then(roles => { 34 | for(let i=0; i { 49 | let token = req.headers['x-access-token']; 50 | 51 | User.findByPk(req.userId) 52 | .then(user => { 53 | user.getRoles().then(roles => { 54 | for(let i=0; i { 8 | // -> Check Username is already in use 9 | User.findOne({ 10 | where: { 11 | username: req.body.username 12 | } 13 | }).then(user => { 14 | if(user){ 15 | res.status(400).send("Fail -> Username is already taken!"); 16 | return; 17 | } 18 | 19 | // -> Check Email is already in use 20 | User.findOne({ 21 | where: { 22 | email: req.body.email 23 | } 24 | }).then(user => { 25 | if(user){ 26 | res.status(400).send("Fail -> Email is already in use!"); 27 | return; 28 | } 29 | 30 | next(); 31 | }); 32 | }); 33 | } 34 | 35 | checkRolesExisted = (req, res, next) => { 36 | for(let i=0; i Does NOT exist Role = " + req.body.roles[i]); 39 | return; 40 | } 41 | } 42 | next(); 43 | } 44 | 45 | const signUpVerify = {}; 46 | signUpVerify.checkDuplicateUserNameOrEmail = checkDuplicateUserNameOrEmail; 47 | signUpVerify.checkRolesExisted = checkRolesExisted; 48 | 49 | module.exports = signUpVerify; -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-jwt-auth", 3 | "version": "1.0.0", 4 | "description": "Build Nodejs JWT Authentication RestAPIs ", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "nodejs", 11 | "jwt", 12 | "authentication", 13 | "restapis" 14 | ], 15 | "author": "https://loizenai.com", 16 | "license": "ISC", 17 | "dependencies": { 18 | "bcryptjs": "^2.4.3", 19 | "express": "^4.17.1", 20 | "jsonwebtoken": "^8.5.1", 21 | "mysql2": "^2.1.0", 22 | "sequelize": "^5.21.12" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Angular 10 Nodejs JWT Token Based Authentication Example - Backend-Sourcecode/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()) 5 | 6 | require('./app/router/router.js')(app); 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | const Role = db.role; 11 | 12 | // force: true will drop the table if it already exists 13 | db.sequelize.sync({force: true}).then(() => { 14 | console.log('Drop and Resync with { force: true }'); 15 | initial(); 16 | }); 17 | 18 | //require('./app/route/project.route.js')(app); 19 | 20 | // Create a Server 21 | var server = app.listen(8080, function () { 22 | 23 | var host = server.address().address 24 | var port = server.address().port 25 | 26 | console.log("App listening at http://%s:%s", host, port) 27 | }) 28 | 29 | 30 | function initial(){ 31 | Role.create({ 32 | id: 1, 33 | name: "USER" 34 | }); 35 | 36 | Role.create({ 37 | id: 2, 38 | name: "ADMIN" 39 | }); 40 | 41 | Role.create({ 42 | id: 3, 43 | name: "PM" 44 | }); 45 | } -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/README.md: -------------------------------------------------------------------------------- 1 | Backend Development - Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 2 | *** 3 | Link: https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 4 | 5 | Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser. Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google. In the tutorial, I introduce how to build a Angular Nodejs CRUD RestAPIs Fullstack Project with POST/GET/PUT/DELETE requests with step by step coding examples. 6 | 7 | Related posts: 8 | 1. Angular Django CRUD RestAPIs Application Examples – Fullstack Angular 10 + Django + MySQL/PostgreSQL Tutorial 9 | https://loizenai.com/angular-django-crud-restapis-application-examples-fullstack-angular-10-django-mysql-postgresql/ 10 | 11 | 2. Angular CRUD Application with SpringBoot and MySQL/PostgreSQL RestAPIs – Fullstack Angular 10-9-8 HttpClient Post/Get/Put/Delete 12 | https://loizenai.com/angular-crud-application-with-springboot-and-mysql-postgresql-restapis-fullstack-angular-httpclient-post-get-put-delete/ 13 | 14 | 3. Build Angular Table Pagination Filtering Sorting with SpringBoot RestAPIs + Bootstrap Example – Angular 10-9-8-6 Tutorial 15 | https://loizenai.com/build-angular-table-pagination-filtering-sorting-with-springboot-restapis-example-tutorial/ 16 | -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/app/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const db = require('../config/db.config.js'); 2 | const Customer = db.Customer; 3 | 4 | /** 5 | * Save a Customer object to database MySQL/PostgreSQL 6 | * @param {*} req 7 | * @param {*} res 8 | */ 9 | exports.create = (req, res) => { 10 | let customer = {}; 11 | 12 | try{ 13 | // Building Customer object from upoading request's body 14 | customer.firstname = req.body.firstname; 15 | customer.lastname = req.body.lastname; 16 | customer.address = req.body.address; 17 | customer.age = req.body.age; 18 | 19 | // Save to MySQL database 20 | Customer.create(customer).then(result => { 21 | // send uploading message to client 22 | res.status(200).json({ 23 | message: "Upload Successfully a Customer with id = " + result.id, 24 | customers: [result], 25 | error: "" 26 | }); 27 | }); 28 | }catch(error){ 29 | res.status(500).json({ 30 | message: "Fail!", 31 | customers: [], 32 | error: error.message 33 | }); 34 | } 35 | } 36 | 37 | /** 38 | * Retrieve Customer information from database 39 | * @param {*} req 40 | * @param {*} res 41 | */ 42 | exports.retrieveAllCustomers = (req, res) => { 43 | // find all Customer information from 44 | try{ 45 | Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address']}) 46 | .then(customerInfos => { 47 | res.status(200).json({ 48 | message: "Get all Customers' Infos Successfully!", 49 | customers: customerInfos, 50 | error: "" 51 | }); 52 | }) 53 | }catch(error) { 54 | // log on console 55 | console.log(error); 56 | 57 | res.status(500).json({ 58 | message: "Error!", 59 | customers: [], 60 | error: error 61 | }); 62 | } 63 | } 64 | 65 | /** 66 | * Updating a Customer 67 | * @param {*} req 68 | * @param {*} res 69 | */ 70 | exports.updateById = async (req, res) => { 71 | try{ 72 | let customerId = req.params.id; 73 | let customer = await Customer.findByPk(customerId); 74 | 75 | if(!customer){ 76 | // return a response to client 77 | res.status(404).json({ 78 | message: "Not Found for updating a customer with id = " + customerId, 79 | customers: [], 80 | error: "404" 81 | }); 82 | } else { 83 | // update new change to database 84 | let updatedObject = { 85 | firstname: req.body.firstname, 86 | lastname: req.body.lastname, 87 | address: req.body.address, 88 | age: req.body.age 89 | } 90 | let result = await Customer.update(updatedObject, {returning: true, where: {id: customerId}}); 91 | 92 | // return the response to client 93 | if(!result) { 94 | res.status(500).json({ 95 | message: "Error -> Can not update a customer with id = " + req.params.id, 96 | error: "Can NOT Updated", 97 | customers: [] 98 | }); 99 | } 100 | 101 | res.status(200).json({ 102 | message: "Update successfully a Customer with id = " + customerId, 103 | customers: [updatedObject], 104 | error: "" 105 | }); 106 | } 107 | } catch(error){ 108 | res.status(500).json({ 109 | message: "Error -> Can not update a customer with id = " + req.params.id, 110 | error: error.message, 111 | customers: [] 112 | 113 | }); 114 | } 115 | } 116 | 117 | /** 118 | * Delete a Customer by ID 119 | * @param {*} req 120 | * @param {*} res 121 | */ 122 | exports.deleteById = async (req, res) => { 123 | try{ 124 | let customerId = req.params.id; 125 | let customer = await Customer.findByPk(customerId); 126 | 127 | if(!customer){ 128 | res.status(404).json({ 129 | message: "Does Not exist a Customer with id = " + customerId, 130 | error: "404", 131 | customers: [] 132 | }); 133 | } else { 134 | await customer.destroy(); 135 | res.status(200).json({ 136 | message: "Delete Successfully a Customer with id = " + customerId, 137 | customers: [customer], 138 | error: "" 139 | }); 140 | } 141 | } catch(error) { 142 | res.status(500).json({ 143 | message: "Error -> Can NOT delete a customer with id = " + req.params.id, 144 | error: error.message, 145 | customers: [] 146 | }); 147 | } 148 | } -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | } 20 | }); 21 | 22 | return Customer; 23 | } -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | let path = __basedir + '/view/'; 7 | 8 | router.get('/', (req,res) => { 9 | console.log("__basedir" + __basedir); 10 | res.sendFile(path + "index.html"); 11 | }); 12 | 13 | router.get('/customers/', (req,res) => { 14 | console.log("__basedir" + __basedir); 15 | res.sendFile(path + "customers.html"); 16 | }); 17 | 18 | router.post('/api/customers/create', customers.create); 19 | router.get('/api/customers/retrieveinfos', customers.retrieveAllCustomers); 20 | router.put('/api/customers/updatebyid/:id', customers.updateById); 21 | router.delete('/api/customers/deletebyid/:id', customers.deleteById); 22 | 23 | module.exports = router; -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-build-crud-application", 3 | "version": "1.0.0", 4 | "description": "Nodejs Build Crud Application Post/Get/Put/Delete to MySQL/PostgreSQL with frontend is bootstrap framework", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "Nodejs", 11 | "RestAPI", 12 | "Express", 13 | "Tutorial", 14 | "MySQL", 15 | "PostgreSQL", 16 | "Bootstrap", 17 | "framework" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parser": "^1.19.0", 23 | "cors": "^2.8.5", 24 | "express": "^4.17.1", 25 | "mysql": "^2.18.1", 26 | "mysql2": "^2.1.0", 27 | "sequelize": "^5.21.13" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/resources/js/delete_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | let customerId = 0; 3 | 4 | $(document).on("click", "#div_customer_table table button.btn_delete", function() { 5 | let btn_id = (event.srcElement.id); 6 | customerId = btn_id.split("_")[2]; 7 | 8 | $("div.modal-body") 9 | .text("Do you want delete a Customer with id = " + customerId + " ?"); 10 | }); 11 | 12 | $(document).on("click", "#model-delete-btn", function() { 13 | $.ajax({ 14 | url: '/api/customer/deletebyid/' + customerId, 15 | type: 'DELETE', 16 | success: function(response) { 17 | $("div.modal-body") 18 | .text("Delete successfully a Customer with id = " + customerId + "!"); 19 | 20 | $("#model-delete-btn").remove(); 21 | $("button.btn.btn-secondary").text("Close"); 22 | 23 | // delete the customer row on html page 24 | let row_id = "tr_" + customerId; 25 | $("#" + row_id).remove(); 26 | $("#div_customer_updating").css({"display": "none"}); 27 | }, 28 | error: function(error){ 29 | console.log(error); 30 | $("#div_customer_updating").css({"display": "none"}); 31 | alert("Error -> " + error); 32 | } 33 | }); 34 | }); 35 | }); -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/resources/js/get_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | (function(){ 3 | $.ajax({ 4 | type : "GET", 5 | url : "/api/customer/retrieveinfos", 6 | success: function(response){ 7 | $.each(response.customerInfos, (i, customer) => { 8 | 9 | /* */ 12 | 13 | let deleteButton = ''; 18 | 19 | let get_More_Info_Btn = '' + 22 | customer.id + 23 | ''; 24 | 25 | let tr_id = 'tr_' + customer.id; 26 | let customerRow = '' + 27 | '' + get_More_Info_Btn + '' + 28 | '' + customer.firstname.toUpperCase() + '' + 29 | '' + customer.address + '' + 30 | '' + deleteButton + '' + 31 | ''; 32 | $('#customerTable tbody').append(customerRow); 33 | }); 34 | }, 35 | error : function(e) { 36 | alert("ERROR: ", e); 37 | console.log("ERROR: ", e); 38 | } 39 | }); 40 | })(); 41 | 42 | (function(){ 43 | let pathname = window.location.pathname; 44 | if (pathname == "/customers/") { 45 | $(".nav .nav-item a:last").addClass("active"); 46 | } 47 | })(); 48 | }); -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/resources/js/post_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | $("#add_new_customer").submit(function(evt) { 3 | evt.preventDefault(); 4 | 5 | // PREPARE FORM DATA 6 | let formData = { 7 | firstname : $("#firstname").val(), 8 | lastname : $("#lastname").val(), 9 | address: $("#address").val(), 10 | age: $("#age").val() 11 | } 12 | 13 | $.ajax({ 14 | url: '/api/customer/create', 15 | type: 'POST', 16 | contentType : "application/json", 17 | data: JSON.stringify(formData), 18 | dataType : 'json', 19 | async: false, 20 | cache: false, 21 | success: function (response) { 22 | let customer = response.customer; 23 | let customerString = "{ name: " + customer.firstname + " " + customer.lastname + 24 | ", address: " + customer.address + 25 | ", age: " + customer.age + " }" 26 | let successAlert = '
' + 27 | '' + 28 | '' + response.message + ' Customer\'s Info = ' + customerString; 29 | '
' 30 | $("#response").append(successAlert); 31 | $("#response").css({"display": "block"}); 32 | 33 | resetUploadForm(); 34 | }, 35 | error: function (response) { 36 | let errorAlert = '
' + 37 | '' + 38 | '' + response.message + '' + ' ,Error: ' + message.error + 39 | '
' 40 | $("#response").append(errorAlert); 41 | $("#response").css({"display": "block"}); 42 | 43 | resetUploadForm(); 44 | } 45 | }); 46 | }); 47 | 48 | function resetUploadForm(){ 49 | $("#firstname").val(""); 50 | $("#lastname").val(""); 51 | $("#address").val(""); 52 | $("#age").val(""); 53 | } 54 | 55 | (function(){ 56 | let pathname = window.location.pathname; 57 | if(pathname === "/"){ 58 | $(".nav .nav-item a:first").addClass("active"); 59 | } else if (pathname == "/customers") { 60 | $(".nav .nav-item a:last").addClass("active"); 61 | } 62 | })(); 63 | }); 64 | -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/resources/js/update_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | $("#update_customer_form").submit(function(evt) { 3 | evt.preventDefault(); 4 | try { 5 | let customerId = $("#customer_id").val(); 6 | 7 | // PREPARE FORM DATA 8 | let formData = { 9 | firstname : $("#customer_first_name").val(), 10 | lastname : $("#customer_last_name").val(), 11 | address: $("#customer_address").val(), 12 | age: $("#customer_age").val() 13 | } 14 | 15 | $.ajax({ 16 | url: '/api/customer/updatebyid/' + customerId + "/", 17 | type: 'PUT', 18 | contentType : "application/json", 19 | data: JSON.stringify(formData), 20 | dataType : 'json', 21 | async: false, 22 | cache: false, 23 | success: function (response) { 24 | let customer = response.customer; 25 | let customerString = "{firstname:" + customer.firstname + 26 | " ,lastname:" + customer.lastname + 27 | ", address:" + customer.address + 28 | ", age:" + customer.age + "}" 29 | let successAlert = '
' + 30 | '' + 31 | '' + response.message + ' Customer\'s Info = ' + customerString; 32 | '
' 33 | 34 | // change the updated data for customer table record 35 | $("#tr_" + customerId + " td.td_first_name").text(customer.firstname.toUpperCase()); 36 | $("#tr_" + customerId + " td.td_address").text(customer.address.toUpperCase()); 37 | 38 | $("#response").empty(); 39 | $("#response").append(successAlert); 40 | $("#response").css({"display": "block"}); 41 | }, 42 | 43 | error: function (response) { 44 | let errorAlert = '
' + 45 | '' + 46 | '' + response.message + '' + ' ,Error: ' + message.error + 47 | '
'; 48 | 49 | $("#response").empty(); 50 | $("#response").append(errorAlert); 51 | $("#response").css({"display": "block"}); 52 | } 53 | }); 54 | } catch(error){ 55 | console.log(error); 56 | alert(error); 57 | } 58 | }); 59 | 60 | $(document).on("click", "table button.btn_id", function(){ 61 | let id_of_button = (event.srcElement.id); 62 | let customerId = id_of_button.split("_")[2]; 63 | 64 | $.ajax({ 65 | url: '/api/customer/findone/' + customerId, 66 | type: 'GET', 67 | success: function(response) { 68 | let customer = response.customer; 69 | $("#customer_id").val(customer.id); 70 | $("#customer_first_name").val(customer.firstname); 71 | $("#customer_last_name").val(customer.lastname); 72 | $("#customer_address").val(customer.address); 73 | $("#customer_age").val(customer.age); 74 | $("#div_customer_updating").css({"display": "block"}); 75 | }, 76 | error: function(error){ 77 | console.log(error); 78 | alert("Error -> " + error); 79 | } 80 | }); 81 | }); 82 | }); -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | // force: true will drop the table if it already exists 11 | db.sequelize.sync({force: true}).then(() => { 12 | console.log('Drop and Resync with { force: true }'); 13 | }); 14 | 15 | let router = require('./app/routers/router.js'); 16 | 17 | const cors = require('cors') 18 | const corsOptions = { 19 | origin: 'http://localhost:4200', 20 | optionsSuccessStatus: 200 21 | } 22 | app.use(cors(corsOptions)); 23 | 24 | app.use(bodyParser.json()); 25 | app.use(express.static('resources')); 26 | app.use('/', router); 27 | 28 | // Create a Server 29 | const server = app.listen(8080, function () { 30 | 31 | let host = server.address().address 32 | let port = server.address().port 33 | 34 | console.log("App listening at http://%s:%s", host, port); 35 | }) -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/view/customers.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Build CRUD Nodejs Application 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 25 |
26 |

Customers Table

27 |
28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
IdNameAddress
40 |
41 |
42 |
43 | 73 |
74 |
75 | 76 | 77 | 99 |
100 | 101 | -------------------------------------------------------------------------------- /Angular Nodejs Fullstack CRUD Application - Backend Development/view/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Build CRUD Nodejs Application 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 23 |
24 |
25 |

Add new Customer

26 |
27 |
28 | 29 | 31 |
32 |
33 | 34 | 36 |
37 |
38 | 39 | 41 |
42 |
43 | 44 | 46 |
47 | 48 |
49 | 51 |
52 |
53 |
54 |
55 | 56 | -------------------------------------------------------------------------------- /Angular-10-Nodejs-MongoDB-Pagination/app/config/mongodb.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | url: 'mongodb+srv://loizenai:loizenai@cluster0.gmd7e.mongodb.net/loizenaidb?retryWrites=true&w=majority' 3 | } -------------------------------------------------------------------------------- /Angular-10-Nodejs-MongoDB-Pagination/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | 3 | const CustomerSchema = mongoose.Schema({ 4 | firstname: String, 5 | lastname: String, 6 | address: String, 7 | salary: { 8 | type: Number, 9 | required: true 10 | }, 11 | age: { 12 | type: Number, 13 | min: 18, 14 | max: 65, 15 | required: true 16 | }, 17 | copyrightby: { 18 | type: String, 19 | default: 'https://loizenai.com' 20 | } 21 | }); 22 | 23 | CustomerSchema.virtual('id').get(function(){ 24 | return this._id.toHexString(); 25 | }); 26 | 27 | // Ensure virtual fields are serialised. 28 | CustomerSchema.set('toJSON', { 29 | virtuals: true 30 | }); 31 | 32 | module.exports = mongoose.model('Customer', CustomerSchema); -------------------------------------------------------------------------------- /Angular-10-Nodejs-MongoDB-Pagination/app/routes/customer.router.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | 3 | var customers = require('../controllers/customer.controller.js'); 4 | 5 | // Create a new Customer 6 | app.post('/api/customers/create', customers.create); 7 | app.get('/api/customers/salaries', customers.getSalaries); 8 | app.get('/api/customers/pagefiltersort', customers.paginationfilterandsort); 9 | } -------------------------------------------------------------------------------- /Angular-10-Nodejs-MongoDB-Pagination/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-mongodb-pagination", 3 | "version": "1.0.0", 4 | "description": "server side pagination in nodejs mongodb", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "mongodb", 16 | "pagination" 17 | ], 18 | "author": "https://loizenai.com", 19 | "license": "ISC", 20 | "dependencies": { 21 | "body-parse": "^0.1.0", 22 | "cors": "^2.8.5", 23 | "express": "^4.17.1", 24 | "mongoose": "^5.10.3" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Angular-10-Nodejs-MongoDB-Pagination/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()); 5 | 6 | const cors = require('cors') 7 | const corsOptions = { 8 | origin: 'http://localhost:4200', 9 | optionsSuccessStatus: 200 10 | } 11 | app.use(cors(corsOptions)); 12 | 13 | // Configuring the database 14 | const dbConfig = require('./app/config/mongodb.config.js'); 15 | const mongoose = require('mongoose'); 16 | 17 | mongoose.Promise = global.Promise; 18 | 19 | // Connecting to the database 20 | mongoose.connect(dbConfig.url, { useNewUrlParser: true, useUnifiedTopology: true }) 21 | .then(() => { 22 | console.log("Successfully connected to MongoDB."); 23 | }).catch(err => { 24 | console.log('Could not connect to MongoDB.'); 25 | process.exit(); 26 | }); 27 | 28 | require('./app/routes/customer.router.js')(app); 29 | // Create a Server 30 | var server = app.listen(8080, function () { 31 | var host = server.address().address 32 | var port = server.address().port 33 | 34 | console.log("App listening at http://%s:%s", host, port) 35 | }) -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/README.md: -------------------------------------------------------------------------------- 1 | Angular 10 Nodejs Pagination RestAPIs + Filtering Sorting Example – Fullstack: Angular + Nodejs RestAPIs+ MySQL Tutorial 2 | https://loizenai.com/angular-10-nodejs-mysql-pagination-filtering-sorting-restapis-example/#testcase-3-angular-pagination-filtering-and-sorting 3 | 4 | Related post: 5 | 1. Nodejs JWT Authentication Example – Express RestAPIs + JSON Web Token + BCryptjs + Sequelize + MySQL/PostgreSQL 6 | https://loizenai.com/nodejs-jwt-authentication-example-with-mysql-postgresql-database/ 7 | 8 | 2. Angular & Nodejs JWT Authentication fullstack Example | Angular 6, 7, 8, 9 – Express RestAPIs + JWT + BCryptjs + Sequelize + MySQL/PostgreSQL 9 | https://loizenai.com/angular-nodejs-jwt-authentication-examples-tutorials/ 10 | 11 | 3. Nodejs MySQL Pagination Filtering Sorting Tutorial – Stack: Express RestAPIs + Sequelize ORM + MySQL database Examples 12 | https://loizenai.com/tutorial-nodejs-mysql-pagination-filtering-sorting-express-restapis-sequelize-orm-example/ 13 | -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | salary: { 21 | type: Sequelize.INTEGER 22 | }, 23 | copyrightby: { 24 | type: Sequelize.STRING, 25 | defaultValue: 'https://loizenai.com' 26 | } 27 | }); 28 | 29 | return Customer; 30 | } -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customers/create', customers.create); 7 | router.get('/api/customers/pagefiltersort', customers.pagingfilteringsorting); 8 | router.get('/api/customers/salaries', customers.getSalaries); 9 | 10 | module.exports = router; -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-pagination-filtering-sorting", 3 | "version": "1.0.0", 4 | "description": "Nodejs pagination filtering sorting", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/github.com/loizenai.git" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "filtering", 16 | "sorting", 17 | "pagination" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "bugs": { 22 | "url": "https://github.com/github.com/loizenai/issues" 23 | }, 24 | "homepage": "https://github.com/github.com/loizenai#readme", 25 | "dependencies": { 26 | "body-parse": "^0.1.0", 27 | "cors": "^2.8.5", 28 | "express": "^4.17.1", 29 | "mysql2": "^2.1.0", 30 | "sequelize": "^6.3.3" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Angular-Nodejs-Pagination - Backend Nodejs Development/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | const db = require('./app/config/db.config.js'); 7 | 8 | // force: true will drop the table if it already exists 9 | db.sequelize.sync({force: true}).then(() => { 10 | console.log('Drop and Resync with { force: true }'); 11 | }); 12 | 13 | let router = require('./app/routers/router.js'); 14 | 15 | const cors = require('cors') 16 | const corsOptions = { 17 | origin: 'http://localhost:4200', 18 | optionsSuccessStatus: 200 19 | } 20 | app.use(cors(corsOptions)); 21 | 22 | app.use(bodyParser.json()); 23 | app.use('/', router); 24 | 25 | // Create a Server 26 | const server = app.listen(8080, function () { 27 | 28 | let host = server.address().address 29 | let port = server.address().port 30 | 31 | console.log("App listening at http://%s:%s", host, port); 32 | }) -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'postgres', 4 | password: '123', 5 | host: 'localhost', 6 | dialect: 'postgres', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/app/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const db = require('../config/db.config.js'); 2 | const Customer = db.Customer; 3 | 4 | /** 5 | * Save a Customer object to database MySQL/PostgreSQL 6 | * @param {*} req 7 | * @param {*} res 8 | */ 9 | exports.create = (req, res) => { 10 | let customer = {}; 11 | 12 | try{ 13 | // Building Customer object from upoading request's body 14 | customer.firstname = req.body.firstname; 15 | customer.lastname = req.body.lastname; 16 | customer.address = req.body.address; 17 | customer.age = req.body.age; 18 | 19 | // Save to MySQL database 20 | Customer.create(customer).then(result => { 21 | // send uploading message to client 22 | res.status(200).json({ 23 | message: "Upload Successfully a Customer with id = " + result.id, 24 | customers: [result], 25 | error: "" 26 | }); 27 | }); 28 | }catch(error){ 29 | res.status(500).json({ 30 | message: "Fail!", 31 | customers: [], 32 | error: error.message 33 | }); 34 | } 35 | } 36 | 37 | /** 38 | * Retrieve Customer information from database 39 | * @param {*} req 40 | * @param {*} res 41 | */ 42 | exports.retrieveAllCustomers = (req, res) => { 43 | // find all Customer information from 44 | try{ 45 | Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address']}) 46 | .then(customerInfos => { 47 | res.status(200).json({ 48 | message: "Get all Customers' Infos Successfully!", 49 | customers: customerInfos, 50 | error: "" 51 | }); 52 | }) 53 | }catch(error) { 54 | // log on console 55 | console.log(error); 56 | 57 | res.status(500).json({ 58 | message: "Error!", 59 | customers: [], 60 | error: error 61 | }); 62 | } 63 | } 64 | 65 | /** 66 | * Updating a Customer 67 | * @param {*} req 68 | * @param {*} res 69 | */ 70 | exports.updateById = async (req, res) => { 71 | try{ 72 | let customerId = req.params.id; 73 | let customer = await Customer.findByPk(customerId); 74 | 75 | if(!customer){ 76 | // return a response to client 77 | res.status(404).json({ 78 | message: "Not Found for updating a customer with id = " + customerId, 79 | customers: [], 80 | error: "404" 81 | }); 82 | } else { 83 | // update new change to database 84 | let updatedObject = { 85 | firstname: req.body.firstname, 86 | lastname: req.body.lastname, 87 | address: req.body.address, 88 | age: req.body.age 89 | } 90 | let result = await Customer.update(updatedObject, {returning: true, where: {id: customerId}}); 91 | 92 | // return the response to client 93 | if(!result) { 94 | res.status(500).json({ 95 | message: "Error -> Can not update a customer with id = " + req.params.id, 96 | error: "Can NOT Updated", 97 | customers: [] 98 | }); 99 | } 100 | 101 | res.status(200).json({ 102 | message: "Update successfully a Customer with id = " + customerId, 103 | customers: [updatedObject], 104 | error: "" 105 | }); 106 | } 107 | } catch(error){ 108 | res.status(500).json({ 109 | message: "Error -> Can not update a customer with id = " + req.params.id, 110 | error: error.message, 111 | customers: [] 112 | 113 | }); 114 | } 115 | } 116 | 117 | /** 118 | * Delete a Customer by ID 119 | * @param {*} req 120 | * @param {*} res 121 | */ 122 | exports.deleteById = async (req, res) => { 123 | try{ 124 | let customerId = req.params.id; 125 | let customer = await Customer.findByPk(customerId); 126 | 127 | if(!customer){ 128 | res.status(404).json({ 129 | message: "Does Not exist a Customer with id = " + customerId, 130 | error: "404", 131 | customers: [] 132 | }); 133 | } else { 134 | await customer.destroy(); 135 | res.status(200).json({ 136 | message: "Delete Successfully a Customer with id = " + customerId, 137 | customers: [customer], 138 | error: "" 139 | }); 140 | } 141 | } catch(error) { 142 | res.status(500).json({ 143 | message: "Error -> Can NOT delete a customer with id = " + req.params.id, 144 | error: error.message, 145 | customers: [] 146 | }); 147 | } 148 | } -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | } 20 | }); 21 | 22 | return Customer; 23 | } -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customers/create', customers.create); 7 | router.get('/api/customers/retrieveinfos', customers.retrieveAllCustomers); 8 | router.put('/api/customers/updatebyid/:id', customers.updateById); 9 | router.delete('/api/customers/deletebyid/:id', customers.deleteById); 10 | 11 | module.exports = router; -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-postgresql-crud-restapis-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs PostgreSQL CRUD Application Post/Get/Put/Delete", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "Nodejs", 11 | "RestAPI", 12 | "Express", 13 | "Tutorial", 14 | "PostgreSQL" 15 | ], 16 | "author": "https://loizenai.com", 17 | "license": "ISC", 18 | "dependencies": { 19 | "body-parser": "^1.19.0", 20 | "cors": "^2.8.5", 21 | "express": "^4.17.1", 22 | "pg": "^8.3.2", 23 | "pg-hstore": "^2.3.3", 24 | "sequelize": "^5.21.13" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Angular-Nodejs-PostgreSQL-CRUD-Application-Backend/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | // force: true will drop the table if it already exists 11 | db.sequelize.sync({force: true}).then(() => { 12 | console.log('Drop and Resync with { force: true }'); 13 | }); 14 | 15 | let router = require('./app/routers/router.js'); 16 | 17 | const cors = require('cors') 18 | const corsOptions = { 19 | origin: 'http://localhost:4200', 20 | optionsSuccessStatus: 200 21 | } 22 | app.use(cors(corsOptions)); 23 | 24 | app.use(bodyParser.json()); 25 | app.use(express.static('resources')); 26 | app.use('/', router); 27 | 28 | // Create a Server 29 | const server = app.listen(8080, function () { 30 | 31 | let host = server.address().address 32 | let port = server.address().port 33 | 34 | console.log("App listening at http://%s:%s", host, port); 35 | }) -------------------------------------------------------------------------------- /Angular10-Nodejs-Express-MongoDB-CRUD-Example/app/config/mongodb.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | url: 'mongodb+srv://loizenai:loizenai@cluster0.esvi3.mongodb.net/loizenaidb' 3 | } -------------------------------------------------------------------------------- /Angular10-Nodejs-Express-MongoDB-CRUD-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | 3 | const CustomerSchema = mongoose.Schema({ 4 | firstname: String, 5 | lastname: String, 6 | address: String, 7 | age: { 8 | type: Number, 9 | min: 18, 10 | max: 65, 11 | required: true 12 | }, 13 | copyrightby: { 14 | type: String, 15 | default: 'https://loizenai.com' 16 | } 17 | }); 18 | 19 | CustomerSchema.virtual('id').get(function(){ 20 | return this._id.toHexString(); 21 | }); 22 | 23 | // Ensure virtual fields are serialised. 24 | CustomerSchema.set('toJSON', { 25 | virtuals: true 26 | }); 27 | 28 | module.exports = mongoose.model('Customer', CustomerSchema); -------------------------------------------------------------------------------- /Angular10-Nodejs-Express-MongoDB-CRUD-Example/app/routes/customer.router.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | 3 | var customers = require('../controllers/customer.controller.js'); 4 | 5 | // Create a new Customer 6 | app.post('/api/customers/create', customers.create); 7 | 8 | // Retrieve all Customer 9 | app.get('/api/customers/retrieveinfos', customers.findall); 10 | 11 | // Update a Customer with Id 12 | app.put('/api/customers/updatebyid/:id', customers.update); 13 | 14 | // Delete a Customer with Id 15 | app.delete('/api/customers/deletebyid/:id', customers.delete); 16 | } -------------------------------------------------------------------------------- /Angular10-Nodejs-Express-MongoDB-CRUD-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-express-mongodb-crud-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs Express CRUD RestAPIs with Mongoose Example", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "crud", 16 | "restapi", 17 | "mongoose", 18 | "example", 19 | "express" 20 | ], 21 | "author": "https://loizenai.com", 22 | "license": "ISC", 23 | "dependencies": { 24 | "body-parser": "^1.19.0", 25 | "cors": "^2.8.5", 26 | "express": "^4.17.1", 27 | "mongoose": "^5.10.2" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Angular10-Nodejs-Express-MongoDB-CRUD-Example/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()) 5 | 6 | const cors = require('cors') 7 | const corsOptions = { 8 | origin: 'http://localhost:4200', 9 | optionsSuccessStatus: 200 10 | } 11 | app.use(cors(corsOptions)); 12 | 13 | // Configuring the database 14 | const dbConfig = require('./app/config/mongodb.config.js'); 15 | const mongoose = require('mongoose'); 16 | 17 | mongoose.Promise = global.Promise; 18 | 19 | // Connecting to the database 20 | mongoose.connect(dbConfig.url, { useNewUrlParser: true, useUnifiedTopology: true }) 21 | .then(() => { 22 | console.log("Successfully connected to MongoDB."); 23 | }).catch(err => { 24 | console.log('Could not connect to MongoDB.'); 25 | process.exit(); 26 | }); 27 | 28 | require('./app/routes/customer.router.js')(app); 29 | // Create a Server 30 | var server = app.listen(8080, function () { 31 | var host = server.address().address 32 | var port = server.address().port 33 | 34 | console.log("App listening at http://%s:%s", host, port) 35 | }) -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/README.md: -------------------------------------------------------------------------------- 1 | Tutorial Article: 2 | 3 | Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request 4 | ----------------------------- 5 | https://loizenai.com/build-nodejs-crud-application-with-mysql-postgresql-express-restapis-ajax-post-get-put-delete-request/ 6 | 7 | In the tutorial, I will introduce how to create a Fullstack Nodejs RestAPIs CRUD Application to MySQL/PostgreSQL database using Express framework and Sequelize ORM for building Backend and using Bootstrap, JQuery Ajax for building frontend client 8 | 9 | Related posts: 10 | 11 | 1. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 12 | https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 13 | 14 | 2. Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request 15 | https://loizenai.com/build-nodejs-crud-application-with-mysql-postgresql-express-restapis-ajax-post-get-put-delete-request/ 16 | 17 | 3. Angular & Nodejs JWT Authentication fullstack Example | Angular 6, 7, 8, 9 – Express RestAPIs + JWT + BCryptjs + Sequelize + MySQL/PostgreSQL 18 | https://loizenai.com/angular-nodejs-jwt-authentication-examples-tutorials/ 19 | -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | } 20 | }); 21 | 22 | return Customer; 23 | } -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | let path = __basedir + '/view/'; 7 | 8 | router.get('/', (req,res) => { 9 | console.log("__basedir" + __basedir); 10 | res.sendFile(path + "index.html"); 11 | }); 12 | 13 | router.get('/customers/', (req,res) => { 14 | console.log("__basedir" + __basedir); 15 | res.sendFile(path + "customers.html"); 16 | }); 17 | 18 | router.post('/api/customer/create', customers.create); 19 | router.get('/api/customer/retrieveinfos', customers.retrieveInfos); 20 | router.get('/api/customer/findone/:id', customers.findById); 21 | router.put('/api/customer/updatebyid/:id', customers.updateById); 22 | router.delete('/api/customer/deletebyid/:id', customers.deleteById); 23 | 24 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-build-crud-application", 3 | "version": "1.0.0", 4 | "description": "Nodejs Build Crud Application Post/Get/Put/Delete to MySQL/PostgreSQL with frontend is bootstrap framework", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "Nodejs", 11 | "RestAPI", 12 | "Express", 13 | "Tutorial", 14 | "MySQL", 15 | "PostgreSQL", 16 | "Bootstrap", 17 | "framework" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parser": "^1.19.0", 23 | "express": "^4.17.1", 24 | "mysql": "^2.18.1", 25 | "mysql2": "^2.1.0", 26 | "sequelize": "^5.21.13" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/resources/js/delete_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | let customerId = 0; 3 | 4 | $(document).on("click", "#div_customer_table table button.btn_delete", function() { 5 | let btn_id = (event.srcElement.id); 6 | customerId = btn_id.split("_")[2]; 7 | 8 | $("div.modal-body") 9 | .text("Do you want delete a Customer with id = " + customerId + " ?"); 10 | }); 11 | 12 | $(document).on("click", "#model-delete-btn", function() { 13 | $.ajax({ 14 | url: '/api/customer/deletebyid/' + customerId, 15 | type: 'DELETE', 16 | success: function(response) { 17 | $("div.modal-body") 18 | .text("Delete successfully a Customer with id = " + customerId + "!"); 19 | 20 | $("#model-delete-btn").remove(); 21 | $("button.btn.btn-secondary").text("Close"); 22 | 23 | // delete the customer row on html page 24 | let row_id = "tr_" + customerId; 25 | $("#" + row_id).remove(); 26 | $("#div_customer_updating").css({"display": "none"}); 27 | }, 28 | error: function(error){ 29 | console.log(error); 30 | $("#div_customer_updating").css({"display": "none"}); 31 | alert("Error -> " + error); 32 | } 33 | }); 34 | }); 35 | }); -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/resources/js/get_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | (function(){ 3 | $.ajax({ 4 | type : "GET", 5 | url : "/api/customer/retrieveinfos", 6 | success: function(response){ 7 | $.each(response.customerInfos, (i, customer) => { 8 | 9 | /* */ 12 | 13 | let deleteButton = ''; 18 | 19 | let get_More_Info_Btn = '' + 22 | customer.id + 23 | ''; 24 | 25 | let tr_id = 'tr_' + customer.id; 26 | let customerRow = '' + 27 | '' + get_More_Info_Btn + '' + 28 | '' + customer.firstname.toUpperCase() + '' + 29 | '' + customer.address + '' + 30 | '' + deleteButton + '' + 31 | ''; 32 | $('#customerTable tbody').append(customerRow); 33 | }); 34 | }, 35 | error : function(e) { 36 | alert("ERROR: ", e); 37 | console.log("ERROR: ", e); 38 | } 39 | }); 40 | })(); 41 | 42 | (function(){ 43 | let pathname = window.location.pathname; 44 | if (pathname == "/customers/") { 45 | $(".nav .nav-item a:last").addClass("active"); 46 | } 47 | })(); 48 | }); -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/resources/js/post_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | $("#add_new_customer").submit(function(evt) { 3 | evt.preventDefault(); 4 | 5 | // PREPARE FORM DATA 6 | let formData = { 7 | firstname : $("#firstname").val(), 8 | lastname : $("#lastname").val(), 9 | address: $("#address").val(), 10 | age: $("#age").val() 11 | } 12 | 13 | $.ajax({ 14 | url: '/api/customer/create', 15 | type: 'POST', 16 | contentType : "application/json", 17 | data: JSON.stringify(formData), 18 | dataType : 'json', 19 | async: false, 20 | cache: false, 21 | success: function (response) { 22 | let customer = response.customer; 23 | let customerString = "{ name: " + customer.firstname + " " + customer.lastname + 24 | ", address: " + customer.address + 25 | ", age: " + customer.age + " }" 26 | let successAlert = '
' + 27 | '' + 28 | '' + response.message + ' Customer\'s Info = ' + customerString; 29 | '
' 30 | $("#response").append(successAlert); 31 | $("#response").css({"display": "block"}); 32 | 33 | resetUploadForm(); 34 | }, 35 | error: function (response) { 36 | let errorAlert = '
' + 37 | '' + 38 | '' + response.message + '' + ' ,Error: ' + message.error + 39 | '
' 40 | $("#response").append(errorAlert); 41 | $("#response").css({"display": "block"}); 42 | 43 | resetUploadForm(); 44 | } 45 | }); 46 | }); 47 | 48 | function resetUploadForm(){ 49 | $("#firstname").val(""); 50 | $("#lastname").val(""); 51 | $("#address").val(""); 52 | $("#age").val(""); 53 | } 54 | 55 | (function(){ 56 | let pathname = window.location.pathname; 57 | if(pathname === "/"){ 58 | $(".nav .nav-item a:first").addClass("active"); 59 | } else if (pathname == "/customers") { 60 | $(".nav .nav-item a:last").addClass("active"); 61 | } 62 | })(); 63 | }); 64 | -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/resources/js/update_customer.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function(){ 2 | $("#update_customer_form").submit(function(evt) { 3 | evt.preventDefault(); 4 | try { 5 | let customerId = $("#customer_id").val(); 6 | 7 | // PREPARE FORM DATA 8 | let formData = { 9 | firstname : $("#customer_first_name").val(), 10 | lastname : $("#customer_last_name").val(), 11 | address: $("#customer_address").val(), 12 | age: $("#customer_age").val() 13 | } 14 | 15 | $.ajax({ 16 | url: '/api/customer/updatebyid/' + customerId + "/", 17 | type: 'PUT', 18 | contentType : "application/json", 19 | data: JSON.stringify(formData), 20 | dataType : 'json', 21 | async: false, 22 | cache: false, 23 | success: function (response) { 24 | let customer = response.customer; 25 | let customerString = "{firstname:" + customer.firstname + 26 | " ,lastname:" + customer.lastname + 27 | ", address:" + customer.address + 28 | ", age:" + customer.age + "}" 29 | let successAlert = '
' + 30 | '' + 31 | '' + response.message + ' Customer\'s Info = ' + customerString; 32 | '
' 33 | 34 | // change the updated data for customer table record 35 | $("#tr_" + customerId + " td.td_first_name").text(customer.firstname.toUpperCase()); 36 | $("#tr_" + customerId + " td.td_address").text(customer.address.toUpperCase()); 37 | 38 | $("#response").empty(); 39 | $("#response").append(successAlert); 40 | $("#response").css({"display": "block"}); 41 | }, 42 | 43 | error: function (response) { 44 | let errorAlert = '
' + 45 | '' + 46 | '' + response.message + '' + ' ,Error: ' + message.error + 47 | '
'; 48 | 49 | $("#response").empty(); 50 | $("#response").append(errorAlert); 51 | $("#response").css({"display": "block"}); 52 | } 53 | }); 54 | } catch(error){ 55 | console.log(error); 56 | alert(error); 57 | } 58 | }); 59 | 60 | $(document).on("click", "table button.btn_id", function(){ 61 | let id_of_button = (event.srcElement.id); 62 | let customerId = id_of_button.split("_")[2]; 63 | 64 | $.ajax({ 65 | url: '/api/customer/findone/' + customerId, 66 | type: 'GET', 67 | success: function(response) { 68 | let customer = response.customer; 69 | $("#customer_id").val(customer.id); 70 | $("#customer_first_name").val(customer.firstname); 71 | $("#customer_last_name").val(customer.lastname); 72 | $("#customer_address").val(customer.address); 73 | $("#customer_age").val(customer.age); 74 | $("#div_customer_updating").css({"display": "block"}); 75 | }, 76 | error: function(error){ 77 | console.log(error); 78 | alert("Error -> " + error); 79 | } 80 | }); 81 | }); 82 | }); -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | // force: true will drop the table if it already exists 11 | db.sequelize.sync({force: true}).then(() => { 12 | console.log('Drop and Resync with { force: true }'); 13 | }); 14 | 15 | let router = require('./app/routers/router.js'); 16 | app.use(bodyParser.json()); 17 | app.use(express.static('resources')); 18 | app.use('/', router); 19 | 20 | // Create a Server 21 | const server = app.listen(8080, function () { 22 | 23 | let host = server.address().address 24 | let port = server.address().port 25 | 26 | console.log("App listening at http://%s:%s", host, port); 27 | }) -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/view/customers.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Build CRUD Nodejs Application 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 25 |
26 |

Customers Table

27 |
28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
IdNameAddress
40 |
41 |
42 |
43 | 73 |
74 |
75 | 76 | 77 | 99 |
100 | 101 | -------------------------------------------------------------------------------- /Nodejs Build CRUD Application/view/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Build CRUD Nodejs Application 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 23 |
24 |
25 |

Add new Customer

26 |
27 |
28 | 29 | 31 |
32 |
33 | 34 | 36 |
37 |
38 | 39 | 41 |
42 |
43 | 44 | 46 |
47 | 48 |
49 | 51 |
52 |
53 |
54 |
55 | 56 | -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/README.md: -------------------------------------------------------------------------------- 1 | Tutorial Nodejs Express RestAPIs MySQL with Sequelize Queries Examples 2 | https://loizenai.com/tutorial-nodejs-express-restapis-mysql-sequelize-queries-examples/ 3 | 4 | Related posts: 5 | 1. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 6 | https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 7 | 8 | 2. Nodejs JWT Authentication Example – Express RestAPIs + JSON Web Token + BCryptjs + Sequelize + MySQL/PostgreSQL 9 | https://loizenai.com/nodejs-jwt-authentication-example-with-mysql-postgresql-database/ 10 | 11 | 3. Nodejs RestAPIs Upload Download Multiple Excel Files to MySQL/PostgreSQL – Multer, Sequelize ORM, Exceljs, Read-excel-file 12 | https://loizenai.com/nodejs-restapis-upload-download-multiple-excel-files-to-mysql-postgresql/ 13 | -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | copyrightby: { 21 | type: Sequelize.STRING, 22 | defaultValue: 'https://loizenai.com' 23 | } 24 | }); 25 | 26 | return Customer; 27 | } -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customers/create', customers.create); 7 | router.get('/api/customers/all', customers.retrieveAllCustomers); 8 | router.get('/api/customers/onebyid/:id', customers.getCustomerById); 9 | router.get('/api/customers/filteringbyage', customers.filteringByAge); 10 | router.get('/api/customers/pagination', customers.pagination); 11 | router.get('/api/customers/pagefiltersort', customers.pagingfilteringsorting); 12 | router.put('/api/customers/update/:id', customers.updateById); 13 | router.delete('/api/customers/delete/:id', customers.deleteById); 14 | 15 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-express-restapis-mysql", 3 | "version": "1.0.0", 4 | "description": "Nodejs Create RestAPIs with MySQL database - RestAPI Post/Get/Delete/Put examples", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "restapis", 16 | "mysql", 17 | "tutorials" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parse": "^0.1.0", 23 | "cors": "^2.8.5", 24 | "express": "^4.17.1", 25 | "mysql2": "^2.1.0", 26 | "sequelize": "^6.3.3" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Nodejs RestAPIs Express Sequelize MySQL/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | const db = require('./app/config/db.config.js'); 7 | 8 | // force: true will drop the table if it already exists 9 | db.sequelize.sync({force: true}).then(() => { 10 | console.log('Drop and Resync with { force: true }'); 11 | }); 12 | 13 | let router = require('./app/routers/router.js'); 14 | 15 | const cors = require('cors') 16 | const corsOptions = { 17 | origin: 'http://localhost:4200', 18 | optionsSuccessStatus: 200 19 | } 20 | app.use(cors(corsOptions)); 21 | 22 | app.use(bodyParser.json()); 23 | app.use('/', router); 24 | 25 | // Create a Server 26 | const server = app.listen(8080, function () { 27 | 28 | let host = server.address().address 29 | let port = server.address().port 30 | 31 | console.log("App listening at http://%s:%s", host, port); 32 | }) -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/README.md: -------------------------------------------------------------------------------- 1 | Ajax Pagination Node.js MySQL RestAPIs Example – Client Side Pagination in Node.js Tutorial 2 | https://loizenai.com/ajax-client-side-pagination-in-nodejs-mysql-restapis-example/ 3 | 4 | Related posts: 5 | 1. Angular 10 Nodejs Pagination RestAPIs + Filtering Sorting Example – Fullstack: Angular + Nodejs RestAPIs+ MySQL Tutorial 6 | https://loizenai.com/angular-10-nodejs-mysql-pagination-filtering-sorting-restapis-example/ 7 | 8 | 2. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 9 | https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 10 | 11 | 3. Angular 10 Spring Boot JWT Authentication Example – Angular 6, 8, 9, 10 + Spring Security + MySQL/PostgreSQL 12 | https://loizenai.com/angular-spring-boot-jwt-authentication-example-angular-6-8-9-spring-security-mysql-postgresql/ 13 | 14 | 4. Django RestAPIs Tutorial – Build Post/Get/Put/Delete request Examples to MySQL/PostgreSQL databases 15 | https://loizenai.com/python-django-restapis-tutorial-post-get-put-delete-requests-examples-to-mysql-postgresql-databases/ 16 | -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | salary: { 21 | type: Sequelize.INTEGER 22 | }, 23 | copyrightby: { 24 | type: Sequelize.STRING, 25 | defaultValue: 'https://loizenai.com' 26 | } 27 | }); 28 | 29 | return Customer; 30 | } -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | let path = __basedir + '/view/'; 7 | 8 | router.get('/', (req,res) => { 9 | console.log("__basedir" + __basedir); 10 | res.sendFile(path + "index.html"); 11 | }); 12 | 13 | router.post('/api/customers/create', customers.create); 14 | router.get('/api/customers/pagefiltersort', customers.pagingfilteringsorting); 15 | router.get('/api/customers/salaries', customers.getSalaries); 16 | 17 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-pagination-filtering-sorting", 3 | "version": "1.0.0", 4 | "description": "Nodejs pagination filtering sorting", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/github.com/loizenai.git" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "filtering", 16 | "sorting", 17 | "pagination" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "bugs": { 22 | "url": "https://github.com/github.com/loizenai/issues" 23 | }, 24 | "homepage": "https://github.com/github.com/loizenai#readme", 25 | "dependencies": { 26 | "body-parse": "^0.1.0", 27 | "cors": "^2.8.5", 28 | "express": "^4.17.1", 29 | "mysql2": "^2.1.0", 30 | "sequelize": "^6.3.3" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | const db = require('./app/config/db.config.js'); 7 | 8 | global.__basedir = __dirname; 9 | 10 | // force: true will drop the table if it already exists 11 | db.sequelize.sync({force: true}).then(() => { 12 | console.log('Drop and Resync with { force: true }'); 13 | }); 14 | 15 | let router = require('./app/routers/router.js'); 16 | 17 | const cors = require('cors') 18 | const corsOptions = { 19 | origin: 'http://localhost:4200', 20 | optionsSuccessStatus: 200 21 | } 22 | app.use(cors(corsOptions)); 23 | 24 | app.use(bodyParser.json()); 25 | app.use(express.static('resources')); 26 | app.use('/', router); 27 | 28 | // Create a Server 29 | const server = app.listen(8080, function () { 30 | 31 | let host = server.address().address 32 | let port = server.address().port 33 | 34 | console.log("App listening at http://%s:%s", host, port); 35 | }) -------------------------------------------------------------------------------- /Nodejs-Ajax-MySQL-Pagination-Examples/view/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Ajax Paging Table 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |
19 |
21 |

Bootstrap + Ajax + Node.js Pagination

22 |
23 |

24 | @Copyright by 25 | https://loizenai.com 26 | 27 |
28 | youtube: 29 | loizenai 30 | 31 |

32 |
33 |
Do you want sorting by salary?
34 |
35 |
36 | 37 | 38 |
39 | 40 | 41 |
42 |
43 | 44 |
45 |
46 | 47 | 49 |
50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 |
IdFirstnameLastnameAgeSalaryAddressCopyright By
66 | 67 |
    68 |
69 |
70 |
71 |
72 | 73 | -------------------------------------------------------------------------------- /Nodejs-Express-MongoDB-CRUD-Example/app/config/mongodb.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | url: 'mongodb+srv://loizenai:loizenai@cluster0.esvi3.mongodb.net/loizenaidb' 3 | } -------------------------------------------------------------------------------- /Nodejs-Express-MongoDB-CRUD-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | 3 | const CustomerSchema = mongoose.Schema({ 4 | firstname: String, 5 | lastname: String, 6 | address: String, 7 | age: { 8 | type: Number, 9 | min: 18, 10 | max: 65, 11 | required: true 12 | }, 13 | copyrightby: { 14 | type: String, 15 | default: 'https://loizenai.com' 16 | } 17 | }); 18 | 19 | module.exports = mongoose.model('Customer', CustomerSchema); -------------------------------------------------------------------------------- /Nodejs-Express-MongoDB-CRUD-Example/app/routes/customer.router.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | 3 | var customers = require('../controllers/customer.controller.js'); 4 | 5 | // Create a new Customer 6 | app.post('/api/customer/create', customers.create); 7 | 8 | // Retrieve all Customer 9 | app.get('/api/customer/retrieveinfos', customers.findall); 10 | 11 | // Retrieve a single Customer by Id 12 | app.get('/api/customer/findone/:id', customers.findone); 13 | 14 | // Update a Customer with Id 15 | app.put('/api/customer/updatebyid/:id', customers.update); 16 | 17 | // Delete a Customer with Id 18 | app.delete('/api/customer/deletebyid/:id', customers.delete); 19 | 20 | app.get('/api/customer/filteringbyage', customers.filteringByAge); 21 | 22 | app.get('/api/customer/pagination', customers.pagination); 23 | 24 | app.get('/api/customer/pagefiltersort', customers.paginationfilterandsort); 25 | } -------------------------------------------------------------------------------- /Nodejs-Express-MongoDB-CRUD-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-express-mongodb-crud-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs Express CRUD RestAPIs with Mongoose Example", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "crud", 16 | "restapi", 17 | "mongoose", 18 | "example", 19 | "express" 20 | ], 21 | "author": "https://loizenai.com", 22 | "license": "ISC", 23 | "dependencies": { 24 | "body-parser": "^1.19.0", 25 | "cors": "^2.8.5", 26 | "express": "^4.17.1", 27 | "mongoose": "^5.10.2" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Nodejs-Express-MongoDB-CRUD-Example/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()) 5 | 6 | // Configuring the database 7 | const dbConfig = require('./app/config/mongodb.config.js'); 8 | const mongoose = require('mongoose'); 9 | 10 | mongoose.Promise = global.Promise; 11 | 12 | // Connecting to the database 13 | mongoose.connect(dbConfig.url, { useNewUrlParser: true, useUnifiedTopology: true }) 14 | .then(() => { 15 | console.log("Successfully connected to MongoDB."); 16 | }).catch(err => { 17 | console.log('Could not connect to MongoDB.'); 18 | process.exit(); 19 | }); 20 | 21 | require('./app/routes/customer.router.js')(app); 22 | // Create a Server 23 | var server = app.listen(8080, function () { 24 | var host = server.address().address 25 | var port = server.address().port 26 | 27 | console.log("App listening at http://%s:%s", host, port) 28 | }) -------------------------------------------------------------------------------- /Nodejs-MongoDB-Pagination-Example/app/config/mongodb.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | url: 'mongodb+srv://loizenai:loizenai@cluster0.esvi3.mongodb.net/loizenaidb' 3 | } -------------------------------------------------------------------------------- /Nodejs-MongoDB-Pagination-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | 3 | const CustomerSchema = mongoose.Schema({ 4 | firstname: String, 5 | lastname: String, 6 | address: String, 7 | age: { 8 | type: Number, 9 | min: 18, 10 | max: 65, 11 | required: true 12 | }, 13 | copyrightby: { 14 | type: String, 15 | default: 'https://loizenai.com' 16 | } 17 | }); 18 | 19 | module.exports = mongoose.model('Customer', CustomerSchema); -------------------------------------------------------------------------------- /Nodejs-MongoDB-Pagination-Example/app/routes/customer.router.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | 3 | var customers = require('../controllers/customer.controller.js'); 4 | 5 | // Create a new Customer 6 | app.post('/api/customer/create', customers.create); 7 | 8 | app.get('/api/customer/filteringbyage', customers.filteringByAge); 9 | 10 | app.get('/api/customer/pagination', customers.pagination); 11 | app.get('/api/customer/pagination_v2', customers.pagination); 12 | 13 | app.get('/api/customer/pagefiltersort', customers.paginationfilterandsort); 14 | } -------------------------------------------------------------------------------- /Nodejs-MongoDB-Pagination-Example/list-customers: -------------------------------------------------------------------------------- 1 | { 2 | "firstname": "Jack", 3 | "lastname": "Smith", 4 | "address": "Massachusetts", 5 | "age": 23, 6 | "salary": 4000, 7 | "copyrightby": "https://loizenai.com" 8 | } 9 | 10 | { 11 | "firstname": "Adam", 12 | "lastname": "Johnson", 13 | "address": "New York", 14 | "age": 27, 15 | "salary": 3000, 16 | "copyrightby": "https://loizenai.com" 17 | } 18 | 19 | { 20 | "firstname": "Katherin", 21 | "lastname": "Carter", 22 | "address": "Washington DC", 23 | "age": 23, 24 | "salary": 4000, 25 | "copyrightby": "https://loizenai.com" 26 | } 27 | 28 | { 29 | "firstname": "Jack", 30 | "lastname": "London", 31 | "address": "Nevada", 32 | "age": 33, 33 | "salary": 3000, 34 | "copyrightby": "https://loizenai.com" 35 | } 36 | 37 | { 38 | "firstname": "Jason", 39 | "lastname": "Bourne", 40 | "address": "California", 41 | "age": 23, 42 | "salary": 4000, 43 | "copyrightby": "https://loizenai.com" 44 | } 45 | 46 | { 47 | "firstname": "Blade", 48 | "lastname": "Johnson", 49 | "address": "Ohio", 50 | "age": 18, 51 | "salary": 4000, 52 | "copyrightby": "https://loizenai.com" 53 | } 54 | 55 | { 56 | "firstname": "Carol", 57 | "lastname": "Carter", 58 | "address": "Florida", 59 | "age": 23, 60 | "salary": 3000, 61 | "copyrightby": "https://loizenai.com" 62 | } 63 | 64 | { 65 | "firstname": "Avery", 66 | "lastname": "Alvin", 67 | "address": "Washington DC", 68 | "age": 41, 69 | "salary": 4000, 70 | "copyrightby": "https://loizenai.com" 71 | } 72 | 73 | { 74 | "firstname": "Dana", 75 | "lastname": "Bay", 76 | "address": "Texas", 77 | "age": 23, 78 | "salary": 3500, 79 | "copyrightby": "https://loizenai.com" 80 | } 81 | 82 | { 83 | "firstname": "Tom", 84 | "lastname": "Bourne", 85 | "address": "Colorado", 86 | "age": 28, 87 | "salary": 3000, 88 | "copyrightby": "https://loizenai.com" 89 | } 90 | 91 | { 92 | "firstname": "Ardys", 93 | "lastname": "Bean", 94 | "address": "Alaska", 95 | "age": 23, 96 | "salary": 4000, 97 | "copyrightby": "https://loizenai.com" 98 | } 99 | 100 | { 101 | "firstname": "Carol", 102 | "lastname": "Carter", 103 | "address": "Arizona", 104 | "age": 26, 105 | "salary": 3500, 106 | "copyrightby": "https://loizenai.com" 107 | } 108 | 109 | { 110 | "firstname": "Avery", 111 | "lastname": "Zane", 112 | "address": "Virginia", 113 | "age": 26, 114 | "salary": 4000, 115 | "copyrightby": "https://loizenai.com" 116 | } 117 | 118 | { 119 | "firstname": "Barric", 120 | "lastname": "Weldin", 121 | "address": "Oregon", 122 | "age": 23, 123 | "salary": 3000, 124 | "copyrightby": "https://loizenai.com" 125 | } 126 | 127 | { 128 | "firstname": "Galen", 129 | "lastname": "Wayt", 130 | "address": "Missouri", 131 | "age": 48, 132 | "salary": 4000, 133 | "copyrightby": "https://loizenai.com" 134 | } 135 | 136 | { 137 | "firstname": "Mayer", 138 | "lastname": "Acomb", 139 | "address": "Wisconsin", 140 | "age": 32, 141 | "salary": 3500, 142 | "copyrightby": "https://loizenai.com" 143 | } 144 | 145 | { 146 | "firstname": "Sadie", 147 | "lastname": "Albright", 148 | "address": "Tennessee", 149 | "age": 23, 150 | "salary": 3000, 151 | "copyrightby": "https://loizenai.com" 152 | } 153 | 154 | { 155 | "firstname": "Norvell", 156 | "lastname": "Baily", 157 | "address": "Oregon", 158 | "age": 41, 159 | "salary": 4000, 160 | "copyrightby": "https://loizenai.com" 161 | } 162 | 163 | { 164 | "firstname": "Tanzi", 165 | "lastname": "Baney", 166 | "address": "North Dakota", 167 | "age": 23, 168 | "salary": 3500, 169 | "copyrightby": "https://loizenai.com" 170 | } 171 | 172 | { 173 | "firstname": "Osric", 174 | "lastname": "Callender", 175 | "address": "New Mexico", 176 | "age": 23, 177 | "salary": 3000, 178 | "copyrightby": "https://loizenai.com" 179 | } 180 | 181 | { 182 | "firstname": "Trudy", 183 | "lastname": "Zane", 184 | "address": "Vermont", 185 | "age": 31, 186 | "salary": 4000, 187 | "copyrightby": "https://loizenai.com" 188 | } 189 | 190 | { 191 | "firstname": "Reynold", 192 | "lastname": "Zone", 193 | "address": "Wyoming", 194 | "age": 43, 195 | "salary": 4000, 196 | "copyrightby": "https://loizenai.com" 197 | } 198 | 199 | { 200 | "firstname": "Udele", 201 | "lastname": "Wheetley", 202 | "address": "Michigan", 203 | "age": 37, 204 | "salary": 4000, 205 | "copyrightby": "https://loizenai.com" 206 | } 207 | 208 | { 209 | "firstname": "Blackburn", 210 | "lastname": "Atkinson", 211 | "address": "Illinois", 212 | "age": 23, 213 | "salary": 3000, 214 | "copyrightby": "https://loizenai.com" 215 | } 216 | 217 | { 218 | "firstname": "Cotovatre", 219 | "lastname": "Bailey", 220 | "address": "Delaware", 221 | "age": 23, 222 | "salary": 4000, 223 | "copyrightby": "https://loizenai.com" 224 | } 225 | -------------------------------------------------------------------------------- /Nodejs-MongoDB-Pagination-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-mongodb-pagination", 3 | "version": "1.0.0", 4 | "description": "server side pagination in nodejs mongodb", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "mongodb", 16 | "pagination" 17 | ], 18 | "author": "https://loizenai.com", 19 | "license": "ISC", 20 | "dependencies": { 21 | "body-parse": "^0.1.0", 22 | "express": "^4.17.1", 23 | "mongoose": "^5.10.3" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Nodejs-MongoDB-Pagination-Example/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()) 5 | 6 | // Configuring the database 7 | const dbConfig = require('./app/config/mongodb.config.js'); 8 | const mongoose = require('mongoose'); 9 | 10 | mongoose.Promise = global.Promise; 11 | 12 | // Connecting to the database 13 | mongoose.connect(dbConfig.url, { useNewUrlParser: true, useUnifiedTopology: true }) 14 | .then(() => { 15 | console.log("Successfully connected to MongoDB."); 16 | }).catch(err => { 17 | console.log('Could not connect to MongoDB.'); 18 | process.exit(); 19 | }); 20 | 21 | require('./app/routes/customer.router.js')(app); 22 | // Create a Server 23 | var server = app.listen(8080, function () { 24 | var host = server.address().address 25 | var port = server.address().port 26 | 27 | console.log("App listening at http://%s:%s", host, port) 28 | }) -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/README.md: -------------------------------------------------------------------------------- 1 | Nodejs MySQL Pagination Filtering Sorting Tutorial – Stack: Express RestAPIs + Sequelize ORM + MySQL database Examples 2 | https://loizenai.com/nodejs-mysql-pagination-filtering-sorting-tutorial-stack-express-restapis-sequelize-orm-mysql-database-examples/ 3 | 4 | Related posts: 5 | 1. Nodejs JWT Authentication Example – Express RestAPIs + JSON Web Token + BCryptjs + Sequelize + MySQL/PostgreSQL 6 | https://loizenai.com/nodejs-jwt-authentication-example-with-mysql-postgresql-database/ 7 | 8 | 2. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 9 | https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 10 | 11 | 3. Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request 12 | https://loizenai.com/build-nodejs-crud-application-with-mysql-postgresql-express-restapis-ajax-post-get-put-delete-request/ 13 | 14 | 4. Tutorial Nodejs Express RestAPIs MySQL with Sequelize Queries Examples 15 | https://loizenai.com/tutorial-nodejs-express-restapis-mysql-sequelize-queries-examples/ 16 | -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/app/controllers/controller.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * youtube loizenai 4 | */ 5 | 6 | const db = require('../config/db.config.js'); 7 | const Customer = db.Customer; 8 | 9 | exports.create = (req, res) => { 10 | let customer = {}; 11 | 12 | try{ 13 | // Building Customer object from upoading request's body 14 | customer.firstname = req.body.firstname; 15 | customer.lastname = req.body.lastname; 16 | customer.address = req.body.address; 17 | customer.age = req.body.age; 18 | 19 | // Save to MySQL database 20 | Customer.create(customer).then(result => { 21 | // send uploading message to client 22 | res.status(200).json({ 23 | message: "Upload Successfully a Customer with id = " + result.id, 24 | customer: result, 25 | }); 26 | }); 27 | }catch(error){ 28 | res.status(500).json({ 29 | message: "Fail!", 30 | error: error.message 31 | }); 32 | } 33 | } 34 | 35 | exports.pagination = (req, res) => { 36 | try{ 37 | let page = parseInt(req.query.page); 38 | let limit = parseInt(req.query.limit); 39 | 40 | const offset = page ? page * limit : 0; 41 | 42 | Customer.findAndCountAll({ limit: limit, offset:offset }) 43 | .then(data => { 44 | const totalPages = Math.ceil(data.count / limit); 45 | const response = { 46 | message: "Paginating is completed! Query parameters: page = " + page + ", limit = " + limit, 47 | data: { 48 | "copyrightby": "https://loizenai.com", 49 | "totalItems": data.count, 50 | "totalPages": totalPages, 51 | "limit": limit, 52 | "currentPageNumber": page + 1, 53 | "currentPageSize": data.rows.length, 54 | "customers": data.rows 55 | } 56 | }; 57 | res.send(response); 58 | }); 59 | }catch(error) { 60 | res.status(500).send({ 61 | message: "Error -> Can NOT complete a paging request!", 62 | error: error.message, 63 | }); 64 | } 65 | } 66 | 67 | exports.filteringByAge = (req, res) => { 68 | let age = req.query.age; 69 | 70 | Customer.findAll({ 71 | attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyrightby'], 72 | where: {age: age} 73 | }) 74 | .then(results => { 75 | res.status(200).json({ 76 | message: "Get all Customers with age = " + age, 77 | totalItems: results.length, 78 | customers: results, 79 | }); 80 | }) 81 | . catch(error => { 82 | console.log(error); 83 | res.status(500).json({ 84 | message: "Error!", 85 | error: error 86 | }); 87 | }); 88 | } 89 | 90 | exports.pagingfilteringsorting = (req, res) => { 91 | try{ 92 | let page = parseInt(req.query.page); 93 | let limit = parseInt(req.query.limit); 94 | let age = parseInt(req.query.age); 95 | 96 | const offset = page ? page * limit : 0; 97 | 98 | console.log("offset = " + offset); 99 | 100 | Customer.findAndCountAll({ 101 | attributes: ['id', 'firstname', 'lastname', 'age', 'address'], 102 | where: {age: age}, 103 | order: [ 104 | ['firstname', 'ASC'], 105 | ['lastname', 'DESC'] 106 | ], 107 | limit: limit, 108 | offset:offset 109 | }) 110 | .then(data => { 111 | const totalPages = Math.ceil(data.count / limit); 112 | const response = { 113 | message: "Pagination Filtering Sorting request is completed! Query parameters: page = " + page + ", limit = " + limit + ", age = " + age, 114 | data: { 115 | "copyrightby": "https://loizenai.com", 116 | "totalItems": data.count, 117 | "totalPages": totalPages, 118 | "limit": limit, 119 | "age-filtering": age, 120 | "currentPageNumber": page + 1, 121 | "currentPageSize": data.rows.length, 122 | "customers": data.rows 123 | } 124 | }; 125 | res.send(response); 126 | }); 127 | }catch(error) { 128 | res.status(500).send({ 129 | message: "Error -> Can NOT complete a paging request!", 130 | error: error.message, 131 | }); 132 | } 133 | } -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | copyrightby: { 21 | type: Sequelize.STRING, 22 | defaultValue: 'https://loizenai.com' 23 | } 24 | }); 25 | 26 | return Customer; 27 | } -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customers/create', customers.create); 7 | router.get('/api/customers/pagination', customers.pagination); 8 | router.get('/api/customers/filteringbyage', customers.filteringByAge); 9 | router.get('/api/customers/pagefiltersort', customers.pagingfilteringsorting); 10 | 11 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-pagination-filtering-sorting", 3 | "version": "1.0.0", 4 | "description": "Nodejs pagination filtering sorting", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/github.com/loizenai.git" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "filtering", 16 | "sorting", 17 | "pagination" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "bugs": { 22 | "url": "https://github.com/github.com/loizenai/issues" 23 | }, 24 | "homepage": "https://github.com/github.com/loizenai#readme", 25 | "dependencies": { 26 | "body-parse": "^0.1.0", 27 | "cors": "^2.8.5", 28 | "express": "^4.17.1", 29 | "mysql2": "^2.1.0", 30 | "sequelize": "^6.3.3" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Nodejs-Pagination-Filtering-Sorting/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | const db = require('./app/config/db.config.js'); 7 | 8 | // force: true will drop the table if it already exists 9 | db.sequelize.sync({force: true}).then(() => { 10 | console.log('Drop and Resync with { force: true }'); 11 | }); 12 | 13 | let router = require('./app/routers/router.js'); 14 | 15 | const cors = require('cors') 16 | const corsOptions = { 17 | origin: 'http://localhost:4200', 18 | optionsSuccessStatus: 200 19 | } 20 | app.use(cors(corsOptions)); 21 | 22 | app.use(bodyParser.json()); 23 | app.use('/', router); 24 | 25 | // Create a Server 26 | const server = app.listen(8080, function () { 27 | 28 | let host = server.address().address 29 | let port = server.address().port 30 | 31 | console.log("App listening at http://%s:%s", host, port); 32 | }) -------------------------------------------------------------------------------- /Nodejs-PostgreSQL-CRUD-Example/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * youtube loizenai 4 | */ 5 | 6 | const env = require('./env.js'); 7 | 8 | const Sequelize = require('sequelize'); 9 | const sequelize = new Sequelize(env.database, env.username, env.password, { 10 | host: env.host, 11 | dialect: env.dialect, 12 | operatorsAliases: false, 13 | 14 | pool: { 15 | max: env.max, 16 | min: env.pool.min, 17 | acquire: env.pool.acquire, 18 | idle: env.pool.idle 19 | } 20 | }); 21 | 22 | const db = {}; 23 | 24 | db.Sequelize = Sequelize; 25 | db.sequelize = sequelize; 26 | 27 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 28 | 29 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs-PostgreSQL-CRUD-Example/app/config/env.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * youtube loizenai 4 | */ 5 | 6 | const env = { 7 | database: 'loizenaidb', 8 | username: 'postgres', 9 | password: '123', 10 | host: 'localhost', 11 | dialect: 'postgres', 12 | pool: { 13 | max: 5, 14 | min: 0, 15 | acquire: 30000, 16 | idle: 10000 17 | } 18 | }; 19 | 20 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs-PostgreSQL-CRUD-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * youtube loizenai 4 | */ 5 | 6 | module.exports = (sequelize, Sequelize) => { 7 | const Customer = sequelize.define('customer', { 8 | id: { 9 | type: Sequelize.INTEGER, 10 | autoIncrement: true, 11 | primaryKey: true 12 | }, 13 | firstname: { 14 | type: Sequelize.STRING 15 | }, 16 | lastname: { 17 | type: Sequelize.STRING 18 | }, 19 | address: { 20 | type: Sequelize.STRING 21 | }, 22 | age: { 23 | type: Sequelize.INTEGER 24 | }, 25 | copyrightby: { 26 | type: Sequelize.STRING, 27 | defaultValue: 'https://loizenai.com' 28 | } 29 | }); 30 | 31 | return Customer; 32 | } -------------------------------------------------------------------------------- /Nodejs-PostgreSQL-CRUD-Example/app/routers/router.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * youtube loizenai 4 | */ 5 | 6 | let express = require('express'); 7 | let router = express.Router(); 8 | 9 | const customers = require('../controllers/controller.js'); 10 | 11 | router.post('/api/customers/create', customers.create); 12 | router.get('/api/customers/all', customers.retrieveAllCustomers); 13 | router.get('/api/customers/onebyid/:id', customers.getCustomerById); 14 | router.get('/api/customers/filteringbyage', customers.filteringByAge); 15 | router.get('/api/customers/pagination', customers.pagination); 16 | router.get('/api/customers/pagefiltersort', customers.pagingfilteringsorting); 17 | router.put('/api/customers/update/:id', customers.updateById); 18 | router.delete('/api/customers/delete/:id', customers.deleteById); 19 | 20 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-PostgreSQL-CRUD-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-postgresql-crud-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs PostgreSQL CRUD Example", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "nodejs", 11 | "crud", 12 | "postgresql", 13 | "example" 14 | ], 15 | "author": "https://loizenai.com", 16 | "license": "ISC", 17 | "dependencies": { 18 | "body-parser": "^1.19.0", 19 | "cors": "^2.8.5", 20 | "express": "^4.17.1", 21 | "pg": "^8.3.2", 22 | "pg-hstore": "^2.3.3", 23 | "sequelize": "^6.3.4" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Nodejs-PostgreSQL-CRUD-Example/server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * youtube loizenai 4 | */ 5 | 6 | const express = require('express'); 7 | const app = express(); 8 | 9 | var bodyParser = require('body-parser'); 10 | 11 | const db = require('./app/config/db.config.js'); 12 | 13 | // force: true will drop the table if it already exists 14 | db.sequelize.sync({force: true}).then(() => { 15 | console.log('Drop and Resync with { force: true }'); 16 | }); 17 | 18 | let router = require('./app/routers/router.js'); 19 | 20 | const cors = require('cors') 21 | const corsOptions = { 22 | origin: 'http://localhost:4200', 23 | optionsSuccessStatus: 200 24 | } 25 | app.use(cors(corsOptions)); 26 | 27 | app.use(bodyParser.json()); 28 | app.use('/', router); 29 | 30 | // Create a Server 31 | const server = app.listen(8080, function () { 32 | 33 | let host = server.address().address 34 | let port = server.address().port 35 | 36 | console.log("App listening at http://%s:%s", host, port); 37 | }) -------------------------------------------------------------------------------- /Nodejs-React-Integration-Example/README.md: -------------------------------------------------------------------------------- 1 | https://loizenai.com/integrate-reactjs-nodejs-tutorial/ 2 | 3 | How to Integrate Reactjs with Nodejs Tutorial 4 | 5 | React is an open-source, front end, JavaScript library for building user interfaces or UI components. React can be used as a base in the development of single-page or mobile. So in the tutorial, I introduce a tutorial: “How to Integrate Reactjs with Nodejs example” with the details steps and running sourcecode. 6 | -------------------------------------------------------------------------------- /Nodejs-React-Integration-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-react-integration", 3 | "version": "1.0.0", 4 | "description": "Nodejs React Integration", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "Nodejs", 15 | "reactjs", 16 | "integration" 17 | ], 18 | "author": "https://loizenai.com", 19 | "license": "ISC", 20 | "dependencies": { 21 | "express": "^4.17.1" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Nodejs-React-Integration-Example/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | let path = __dirname + '/views/'; 5 | 6 | app.use(express.static('views')); 7 | 8 | // Create a Server 9 | const server = app.listen(8080, function () { 10 | 11 | let host = server.address().address 12 | let port = server.address().port 13 | 14 | console.log("App listening at http://%s:%s", host, port); 15 | }) 16 | 17 | // respond with "hello world" when a GET request is made to the homepage 18 | app.get('/api/customer', function (req, res) { 19 | res.json({ 20 | firstname: "Jack", 21 | lastname: "Smith", 22 | age: 23, 23 | address: "374 William S Canning Blvd", 24 | copyrightby: "https://loizenai.com" 25 | }) 26 | }) 27 | 28 | app.get('/', function (req,res) { 29 | res.sendFile(path + "index.html"); 30 | }); -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/README.md: -------------------------------------------------------------------------------- 1 | https://loizenai.com/reactjs-nodejs-mongodb-crud/ 2 | 3 | Reactjs Nodejs MongoDB CRUD Example – MERN Stack Application 4 | 5 | In the tutorial, I introduce how to build an “React.js Nodejs CRUD MongoDB Example” project with the help of Ajax to POST/GET/PUT/DELETE requests with step by step coding examples: 6 | 7 | – Nodejs project produces CRUD RestAPIs with MongoDB database using the supporting of Mongoose ODM. 8 | – React.js project will consume the Nodejs CRUD RestAPIs by Ajax then show up on Reactjs component’s views. 9 | 10 | https://loizenai.com/reactjs-nodejs-mongodb-crud/ 11 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/app/config/mongodb.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | url: 'mongodb+srv://loizenai:12345@cluster0.uhqpv.mongodb.net/loizenaidb?retryWrites=true&w=majority' 3 | } -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/app/controllers/customer.controller.js: -------------------------------------------------------------------------------- 1 | const Customer = require('../models/customer.model.js'); 2 | 3 | // POST a Customer 4 | exports.createCustomer = (req, res) => { 5 | 6 | const customer = new Customer({ 7 | firstname: req.body.firstname, 8 | lastname: req.body.lastname, 9 | age: req.body.age, 10 | address: req.body.address, 11 | }); 12 | 13 | // Save a Customer in the MongoDB 14 | customer.save().then(data => { 15 | res.status(200).json(data); 16 | }).catch(err => { 17 | res.status(500).json({ 18 | message: "Fail!", 19 | error: err.message 20 | }); 21 | }); 22 | }; 23 | 24 | // FETCH all Customers 25 | exports.customers = (req, res) => { 26 | Customer.find().select('-__v').then(customerInfos => { 27 | res.status(200).json(customerInfos); 28 | }).catch(error => { 29 | // log on console 30 | console.log(error); 31 | 32 | res.status(500).json({ 33 | message: "Error!", 34 | error: error 35 | }); 36 | }); 37 | }; 38 | 39 | // get a Customer by Id 40 | exports.getCustomer = (req, res) => { 41 | Customer.findById(req.params.id).select('-__v') 42 | .then(customer => { 43 | res.status(200).json(customer); 44 | }).catch(err => { 45 | if(err.kind === 'ObjectId') { 46 | return res.status(404).send({ 47 | message: "Customer not found with id " + req.params.id, 48 | error: err 49 | }); 50 | } 51 | return res.status(500).send({ 52 | message: "Error retrieving Customer with id " + req.params.id, 53 | error: err 54 | }); 55 | }); 56 | }; 57 | 58 | // UPDATE a Customer 59 | exports.updateCustomer = (req, res) => { 60 | // Find customer and update it 61 | Customer.findByIdAndUpdate( 62 | req.body._id, 63 | { 64 | firstname: req.body.firstname, 65 | lastname: req.body.lastname, 66 | age: req.body.age, 67 | address: req.body.address 68 | }, 69 | {new: true} 70 | ).select('-__v') 71 | .then(customer => { 72 | if(!customer) { 73 | return res.status(404).send({ 74 | message: "Error -> Can NOT update a customer with id = " + req.params.id, 75 | error: "Not Found!" 76 | }); 77 | } 78 | 79 | res.status(200).json(customer); 80 | }).catch(err => { 81 | return res.status(500).send({ 82 | message: "Error -> Can not update a customer with id = " + req.params.id, 83 | error: err.message 84 | }); 85 | }); 86 | }; 87 | 88 | // DELETE a Customer 89 | exports.deleteCustomer = (req, res) => { 90 | let customerId = req.params.id 91 | 92 | Customer.findByIdAndRemove(customerId).select('-__v -_id') 93 | .then(customer => { 94 | if(!customer) { 95 | res.status(404).json({ 96 | message: "Does Not exist a Customer with id = " + customerId, 97 | error: "404", 98 | }); 99 | } 100 | res.status(200).json({}); 101 | }).catch(err => { 102 | return res.status(500).send({ 103 | message: "Error -> Can NOT delete a customer with id = " + customerId, 104 | error: err.message 105 | }); 106 | }); 107 | }; -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose'); 2 | 3 | const CustomerSchema = mongoose.Schema({ 4 | firstname: String, 5 | lastname: String, 6 | address: String, 7 | age: { 8 | type: Number, 9 | min: 18, 10 | max: 65, 11 | required: true 12 | }, 13 | copyrightby: { 14 | type: String, 15 | default: 'https://loizenai.com' 16 | } 17 | }); 18 | 19 | module.exports = mongoose.model('Customer', CustomerSchema); -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/app/routes/customer.router.js: -------------------------------------------------------------------------------- 1 | module.exports = function(app) { 2 | 3 | var customers = require('../controllers/customer.controller.js'); 4 | 5 | app.post('/api/customer', customers.createCustomer); 6 | app.get('/api/customer/:id', customers.getCustomer); 7 | app.get('/api/customers', customers.customers); 8 | app.put('/api/customer', customers.updateCustomer); 9 | app.delete('/api/customer/:id', customers.deleteCustomer); 10 | } -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-express-mongodb-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs CRUD restapi MongoDB Example", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "loizenai" 12 | }, 13 | "keywords": [ 14 | "Nodejs", 15 | "MongoDB", 16 | "CRUD", 17 | "RestAPI" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parser": "^1.19.0", 23 | "cors": "^2.8.5", 24 | "express": "^4.17.1", 25 | "mongoose": "^5.10.7", 26 | "pg": "^8.3.3", 27 | "pg-hstore": "^2.3.3" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-MongoDB-CRUD-Example/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()) 5 | 6 | // Configuring the database 7 | const dbConfig = require('./app/config/mongodb.config.js'); 8 | const mongoose = require('mongoose'); 9 | 10 | const Customer = require('./app/models/customer.model.js'); 11 | 12 | mongoose.Promise = global.Promise; 13 | 14 | // Connecting to the database 15 | mongoose.connect(dbConfig.url, { useNewUrlParser: true, useUnifiedTopology: true }) 16 | .then(async () => { 17 | console.log("Successfully connected to MongoDB."); 18 | const customers = [ 19 | { firstname: 'Jack', lastname: 'Smith', 20 | age: 23, address: '374 William S Canning Blvd'}, 21 | { firstname: 'Adam', lastname: 'Johnson', 22 | age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'}, 23 | { firstname: 'Dana', lastname: 'Bay', 24 | age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'}, 25 | ] 26 | 27 | for(let i=0; i { 40 | console.log('Could not connect to MongoDB.'); 41 | process.exit(); 42 | }); 43 | 44 | require('./app/routes/customer.router.js')(app); 45 | // Create a Server 46 | var server = app.listen(8080, function () { 47 | var host = server.address().address 48 | var port = server.address().port 49 | 50 | console.log("App listening at http://%s:%s", host, port) 51 | }) -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/README.md: -------------------------------------------------------------------------------- 1 | Tutorial: Reactjs + Nodejs + MySQL Example 2 | 3 | https://loizenai.com/reactjs-nodejs-crud-mysql/ 4 | 5 | In the tutorial, I introduce how to build an “React.js Nodejs CRUD MySQL Example” project with the help of Ajax to POST/GET/PUT/DELETE requests with step by step coding examples: 6 | 7 | – Nodejs project produces CRUD RestAPIs with MySQL database using the supporting of Sequelize ORM. 8 | – React.js project will consume the Nodejs CRUD RestAPIs by Ajax then show up on Reactjs component’s views. 9 | 10 | List to do: 11 | 12 | – I draw a fullstack overview Diagram Architecture from React.js Frontend to MySQL database through Nodejs RestAPI backend. 13 | – Develop Nodejs CRUD RestAPIs with the supporting of Sequelize ORM. 14 | – Implement Reactjs CRUD application with Ajax fetching APIs to do CRUD request (Post/Get/Put/Delete) to Nodejs Backend APIs. 15 | – I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Reactjs to do CRUD requests to Nodejs RestAPIs Server and save/retrieve data to MySQL database. 16 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | const db = {}; 17 | 18 | db.Sequelize = Sequelize; 19 | db.sequelize = sequelize; 20 | 21 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 22 | 23 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/app/controllers/controller.js: -------------------------------------------------------------------------------- 1 | const db = require('../config/db.config.js'); 2 | const Customer = db.Customer; 3 | 4 | /** 5 | * Save a Customer object to database MySQL/PostgreSQL 6 | * @param {*} req 7 | * @param {*} res 8 | */ 9 | exports.createCustomer = (req, res) => { 10 | let customer = {}; 11 | 12 | try{ 13 | // Building Customer object from upoading request's body 14 | customer.firstname = req.body.firstname; 15 | customer.lastname = req.body.lastname; 16 | customer.address = req.body.address; 17 | customer.age = req.body.age; 18 | 19 | // Save to MySQL database 20 | Customer.create(customer, 21 | {attributes: ['id', 'firstname', 'lastname', 'age', 'address', "copyright"]}) 22 | .then(result => { 23 | res.status(200).json(result); 24 | }); 25 | }catch(error){ 26 | res.status(500).json({ 27 | message: "Fail!", 28 | error: error.message 29 | }); 30 | } 31 | } 32 | 33 | /** 34 | * Retrieve Customer information from database 35 | * @param {*} req 36 | * @param {*} res 37 | */ 38 | exports.customers = (req, res) => { 39 | // find all Customer information from 40 | try{ 41 | Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']}) 42 | .then(customers => { 43 | res.status(200).json(customers); 44 | }) 45 | }catch(error) { 46 | // log on console 47 | console.log(error); 48 | 49 | res.status(500).json({ 50 | message: "Error!", 51 | error: error 52 | }); 53 | } 54 | } 55 | 56 | exports.getCustomer = (req, res) => { 57 | Customer.findByPk(req.params.id, 58 | {attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']}) 59 | .then(customer => { 60 | res.status(200).json(customer); 61 | }).catch(error => { 62 | // log on console 63 | console.log(error); 64 | 65 | res.status(500).json({ 66 | message: "Error!", 67 | error: error 68 | }); 69 | }) 70 | } 71 | 72 | /** 73 | * Updating a Customer 74 | * @param {*} req 75 | * @param {*} res 76 | */ 77 | exports.updateCustomer = async (req, res) => { 78 | try{ 79 | let customer = await Customer.findByPk(req.body.id); 80 | 81 | if(!customer){ 82 | // return a response to client 83 | res.status(404).json({ 84 | message: "Not Found for updating a customer with id = " + customerId, 85 | error: "404" 86 | }); 87 | } else { 88 | // update new change to database 89 | let updatedObject = { 90 | firstname: req.body.firstname, 91 | lastname: req.body.lastname, 92 | address: req.body.address, 93 | age: req.body.age 94 | } 95 | let result = await Customer.update(updatedObject, 96 | { 97 | returning: true, 98 | where: {id: req.body.id}, 99 | attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright'] 100 | } 101 | ); 102 | 103 | // return the response to client 104 | if(!result) { 105 | res.status(500).json({ 106 | message: "Error -> Can not update a customer with id = " + req.params.id, 107 | error: "Can NOT Updated", 108 | }); 109 | } 110 | 111 | res.status(200).json(result); 112 | } 113 | } catch(error){ 114 | res.status(500).json({ 115 | message: "Error -> Can not update a customer with id = " + req.params.id, 116 | error: error.message 117 | }); 118 | } 119 | } 120 | 121 | /** 122 | * Delete a Customer by ID 123 | * @param {*} req 124 | * @param {*} res 125 | */ 126 | exports.deleteCustomer = async (req, res) => { 127 | try{ 128 | let customerId = req.params.id; 129 | let customer = await Customer.findByPk(customerId); 130 | 131 | if(!customer){ 132 | res.status(404).json({ 133 | message: "Does Not exist a Customer with id = " + customerId, 134 | error: "404", 135 | }); 136 | } else { 137 | await customer.destroy(); 138 | res.status(200); 139 | } 140 | } catch(error) { 141 | res.status(500).json({ 142 | message: "Error -> Can NOT delete a customer with id = " + req.params.id, 143 | error: error.message 144 | }); 145 | } 146 | } -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | copyright: { 21 | type: Sequelize.STRING, 22 | defaultValue: "https://loizenai.com" 23 | } 24 | }); 25 | 26 | return Customer; 27 | } 28 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customer', customers.createCustomer); 7 | router.get('/api/customer/:id', customers.getCustomer); 8 | router.get('/api/customers', customers.customers); 9 | router.put('/api/customer', customers.updateCustomer); 10 | router.delete('/api/customer/:id', customers.deleteCustomer); 11 | 12 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-reactjs-restapi-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs Reactjs RestAPI CRUD MySQL database", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "reactjs", 16 | "crud", 17 | "mysql" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parse": "^0.1.0", 23 | "cors": "^2.8.5", 24 | "express": "^4.17.1", 25 | "mysql2": "^2.2.5", 26 | "sequelize": "^6.3.5" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-MySQL-CRUD-Example/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | const Customer = db.Customer; 11 | 12 | let router = require('./app/routers/router.js'); 13 | 14 | const cors = require('cors') 15 | const corsOptions = { 16 | origin: 'http://localhost:4200', 17 | optionsSuccessStatus: 200 18 | } 19 | app.use(cors(corsOptions)); 20 | 21 | app.use(bodyParser.json()); 22 | app.use(express.static('resources')); 23 | app.use('/', router); 24 | 25 | // Create a Server 26 | const server = app.listen(8080, function () { 27 | 28 | let host = server.address().address 29 | let port = server.address().port 30 | 31 | console.log("App listening at http://%s:%s", host, port); 32 | }) 33 | 34 | db.sequelize.sync({force: true}).then(() => { 35 | console.log('Drop and Resync with { force: true }'); 36 | Customer.sync().then(() => { 37 | const customers = [ 38 | { firstname: 'Jack', lastname: 'Smith', 39 | age: 23, address: '374 William S Canning Blvd'}, 40 | { firstname: 'Adam', lastname: 'Johnson', 41 | age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'}, 42 | { firstname: 'Dana', lastname: 'Bay', 43 | age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'}, 44 | ] 45 | 46 | for(let i=0; i { 10 | let customer = {}; 11 | 12 | try{ 13 | // Building Customer object from upoading request's body 14 | customer.firstname = req.body.firstname; 15 | customer.lastname = req.body.lastname; 16 | customer.address = req.body.address; 17 | customer.age = req.body.age; 18 | 19 | // Save to MySQL database 20 | Customer.create(customer, 21 | {attributes: ['id', 'firstname', 'lastname', 'age', 'address', "copyright"]}) 22 | .then(result => { 23 | res.status(200).json(result); 24 | }); 25 | }catch(error){ 26 | res.status(500).json({ 27 | message: "Fail!", 28 | error: error.message 29 | }); 30 | } 31 | } 32 | 33 | /** 34 | * Retrieve Customer information from database 35 | * @param {*} req 36 | * @param {*} res 37 | */ 38 | exports.customers = (req, res) => { 39 | // find all Customer information from 40 | try{ 41 | Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']}) 42 | .then(customers => { 43 | res.status(200).json(customers); 44 | }) 45 | }catch(error) { 46 | // log on console 47 | console.log(error); 48 | 49 | res.status(500).json({ 50 | message: "Error!", 51 | error: error 52 | }); 53 | } 54 | } 55 | 56 | exports.getCustomer = (req, res) => { 57 | Customer.findByPk(req.params.id, 58 | {attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']}) 59 | .then(customer => { 60 | res.status(200).json(customer); 61 | }).catch(error => { 62 | // log on console 63 | console.log(error); 64 | 65 | res.status(500).json({ 66 | message: "Error!", 67 | error: error 68 | }); 69 | }) 70 | } 71 | 72 | /** 73 | * Updating a Customer 74 | * @param {*} req 75 | * @param {*} res 76 | */ 77 | exports.updateCustomer = async (req, res) => { 78 | try{ 79 | let customer = await Customer.findByPk(req.body.id); 80 | 81 | if(!customer){ 82 | // return a response to client 83 | res.status(404).json({ 84 | message: "Not Found for updating a customer with id = " + customerId, 85 | error: "404" 86 | }); 87 | } else { 88 | // update new change to database 89 | let updatedObject = { 90 | firstname: req.body.firstname, 91 | lastname: req.body.lastname, 92 | address: req.body.address, 93 | age: req.body.age 94 | } 95 | let result = await Customer.update(updatedObject, 96 | { 97 | returning: true, 98 | where: {id: req.body.id}, 99 | attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright'] 100 | } 101 | ); 102 | 103 | // return the response to client 104 | if(!result) { 105 | res.status(500).json({ 106 | message: "Error -> Can not update a customer with id = " + req.params.id, 107 | error: "Can NOT Updated", 108 | }); 109 | } 110 | 111 | res.status(200).json(result); 112 | } 113 | } catch(error){ 114 | res.status(500).json({ 115 | message: "Error -> Can not update a customer with id = " + req.params.id, 116 | error: error.message 117 | }); 118 | } 119 | } 120 | 121 | /** 122 | * Delete a Customer by ID 123 | * @param {*} req 124 | * @param {*} res 125 | */ 126 | exports.deleteCustomer = async (req, res) => { 127 | try{ 128 | let customerId = req.params.id; 129 | let customer = await Customer.findByPk(customerId); 130 | 131 | if(!customer){ 132 | res.status(404).json({ 133 | message: "Does Not exist a Customer with id = " + customerId, 134 | error: "404", 135 | }); 136 | } else { 137 | await customer.destroy(); 138 | res.status(200); 139 | } 140 | } catch(error) { 141 | res.status(500).json({ 142 | message: "Error -> Can NOT delete a customer with id = " + req.params.id, 143 | error: error.message 144 | }); 145 | } 146 | } -------------------------------------------------------------------------------- /Nodejs-Reactjs-PostgreSQL-Example/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | firstname: { 9 | type: Sequelize.STRING 10 | }, 11 | lastname: { 12 | type: Sequelize.STRING 13 | }, 14 | address: { 15 | type: Sequelize.STRING 16 | }, 17 | age: { 18 | type: Sequelize.INTEGER 19 | }, 20 | copyright: { 21 | type: Sequelize.STRING, 22 | defaultValue: "https://loizenai.com" 23 | } 24 | }); 25 | 26 | return Customer; 27 | } 28 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-PostgreSQL-Example/app/routers/router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | 4 | const customers = require('../controllers/controller.js'); 5 | 6 | router.post('/api/customer', customers.createCustomer); 7 | router.get('/api/customer/:id', customers.getCustomer); 8 | router.get('/api/customers', customers.customers); 9 | router.put('/api/customer', customers.updateCustomer); 10 | router.delete('/api/customer/:id', customers.deleteCustomer); 11 | 12 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Reactjs-PostgreSQL-Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-reactjs-restapi-example", 3 | "version": "1.0.0", 4 | "description": "Nodejs Reactjs RestAPI CRUD MySQL database", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/loizenai" 12 | }, 13 | "keywords": [ 14 | "nodejs", 15 | "reactjs", 16 | "crud", 17 | "mysql" 18 | ], 19 | "author": "https://loizenai.com", 20 | "license": "ISC", 21 | "dependencies": { 22 | "body-parse": "^0.1.0", 23 | "cors": "^2.8.5", 24 | "express": "^4.17.1", 25 | "mysql2": "^2.2.5", 26 | "pg": "^8.4.2", 27 | "pg-hstore": "^2.3.3", 28 | "sequelize": "^6.3.5" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Nodejs-Reactjs-PostgreSQL-Example/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | var bodyParser = require('body-parser'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | const Customer = db.Customer; 11 | 12 | let router = require('./app/routers/router.js'); 13 | 14 | const cors = require('cors') 15 | const corsOptions = { 16 | origin: 'http://localhost:4200', 17 | optionsSuccessStatus: 200 18 | } 19 | app.use(cors(corsOptions)); 20 | 21 | app.use(bodyParser.json()); 22 | app.use(express.static('resources')); 23 | app.use('/', router); 24 | 25 | // Create a Server 26 | const server = app.listen(8080, function () { 27 | 28 | let host = server.address().address 29 | let port = server.address().port 30 | 31 | console.log("App listening at http://%s:%s", host, port); 32 | }) 33 | 34 | db.sequelize.sync({force: true}).then(() => { 35 | console.log('Drop and Resync with { force: true }'); 36 | Customer.sync().then(() => { 37 | const customers = [ 38 | { firstname: 'Jack', lastname: 'Smith', 39 | age: 23, address: '374 William S Canning Blvd'}, 40 | { firstname: 'Adam', lastname: 'Johnson', 41 | age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'}, 42 | { firstname: 'Dana', lastname: 'Bay', 43 | age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'}, 44 | ] 45 | 46 | for(let i=0; i { 5 | cb(null, __basedir + '/uploads/') 6 | }, 7 | filename: (req, file, cb) => { 8 | cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname) 9 | } 10 | }); 11 | 12 | const upload = multer({storage: storage}); 13 | 14 | module.exports = upload; -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/app/controllers/csv.controller.js: -------------------------------------------------------------------------------- 1 | const stream = require('stream'); 2 | const await = require('await') 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | 6 | const db = require('../config/db.config.js'); 7 | const Customer = db.Customer; 8 | 9 | const csv = require('fast-csv'); 10 | const Json2csvParser = require('json2csv').Parser; 11 | 12 | /** 13 | * Upload Single CSV file/ and Import data to MySQL/PostgreSQL database 14 | * @param {*} req 15 | * @param {*} res 16 | */ 17 | exports.uploadFile = (req, res) => { 18 | try{ 19 | const customers = []; 20 | fs.createReadStream(__basedir + "/uploads/" + req.file.filename) 21 | .pipe(csv.parse({ headers: true })) 22 | .on('error', error => { 23 | console.error(error); 24 | throw error.message; 25 | }) 26 | .on('data', row => { 27 | customers.push(row); 28 | console.log(row); 29 | }) 30 | .on('end', () => { 31 | // Save customers to MySQL/PostgreSQL database 32 | Customer.bulkCreate(customers).then(() => { 33 | const result = { 34 | status: "ok", 35 | filename: req.file.originalname, 36 | message: "Upload Successfully!", 37 | } 38 | 39 | res.json(result); 40 | }); 41 | }); 42 | }catch(error){ 43 | const result = { 44 | status: "fail", 45 | filename: req.file.originalname, 46 | message: "Upload Error! message = " + error.message 47 | } 48 | res.json(result); 49 | } 50 | } 51 | 52 | /** 53 | * Upload multiple Excel Files 54 | * 55 | * @param {*} req 56 | * @param {*} res 57 | */ 58 | exports.uploadMultipleFiles = async (req, res) => { 59 | const messages = []; 60 | 61 | for (const file of req.files) { 62 | try{ 63 | // Parsing CSV Files to data array objects 64 | const csvParserStream = fs.createReadStream(__basedir + "/uploads/" + file.filename) 65 | .pipe(csv.parse({ headers: true })); 66 | 67 | var end = new Promise(function(resolve, reject) { 68 | let customers = []; 69 | 70 | csvParserStream.on('data', object => { 71 | customers.push(object); 72 | console.log(object); 73 | }); 74 | csvParserStream.on('end', () => { 75 | resolve(customers); 76 | }); 77 | csvParserStream.on('error', error => { 78 | console.error(error); 79 | reject 80 | }); // or something like that. might need to close `hash` 81 | }); 82 | 83 | await (async function() { 84 | let customers = await end; 85 | 86 | // save customers to MySQL/PostgreSQL database 87 | await Customer.bulkCreate(customers).then(() => { 88 | const result = { 89 | status: "ok", 90 | filename: file.originalname, 91 | message: "Upload Successfully!", 92 | } 93 | 94 | messages.push(result); 95 | }); 96 | }()); 97 | }catch(error){ 98 | console.log(error); 99 | 100 | const result = { 101 | status: "fail", 102 | filename: file.originalname, 103 | message: "Error -> " + error.message 104 | } 105 | messages.push(result); 106 | } 107 | } 108 | 109 | return res.json(messages); 110 | } 111 | 112 | 113 | exports.downloadFile = (req, res) => { 114 | Customer.findAll({attributes: ['id', 'name', 'address', 'age']}).then(objects => { 115 | const jsonCustomers = JSON.parse(JSON.stringify(objects)); 116 | const csvFields = ['Id', 'Name', 'Address', 'Age']; 117 | const json2csvParser = new Json2csvParser({ csvFields }); 118 | const csvData = json2csvParser.parse(jsonCustomers); 119 | 120 | res.setHeader('Content-disposition', 'attachment; filename=customers.csv'); 121 | res.set('Content-Type', 'text/csv'); 122 | res.status(200).end(csvData); 123 | }); 124 | } -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | name: { 9 | type: Sequelize.STRING 10 | }, 11 | address: { 12 | type: Sequelize.STRING 13 | }, 14 | age: { 15 | type: Sequelize.INTEGER 16 | } 17 | }); 18 | 19 | return Customer; 20 | } -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/app/routers/excel.router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | let upload = require('../config/multer.config.js'); 4 | 5 | const csvWorker = require('../controllers/csv.controller.js'); 6 | 7 | let path = __basedir + '/views/'; 8 | 9 | router.get('/', (req,res) => { 10 | console.log("__basedir" + __basedir); 11 | res.sendFile(path + "index.html"); 12 | }); 13 | 14 | router.post('/api/file/upload', upload.single("file"), csvWorker.uploadFile); 15 | router.post('/api/file/multiple/upload', upload.array('files', 4), csvWorker.uploadMultipleFiles); 16 | 17 | router.get('/api/file', csvWorker.downloadFile); 18 | 19 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-upload-csv-files", 3 | "version": "1.0.0", 4 | "description": "Nodejs Upload Download CSV File to MySQL/PostgreSQL database", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "Nodejs", 11 | "Multer", 12 | "Sequelize", 13 | "Upload-File", 14 | "Download-CSV-File", 15 | "MySQL" 16 | ], 17 | "author": "https://loizenai.com", 18 | "license": "ISC", 19 | "dependencies": { 20 | "await": "^0.2.6", 21 | "express": "^4.17.1", 22 | "fast-csv": "^4.3.0", 23 | "json2csv": "^5.0.1", 24 | "multer": "^1.4.2", 25 | "mysql2": "^2.1.0", 26 | "path": "^0.12.7", 27 | "sequelize": "^5.21.13" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/resources/static/js/uploaddownloadfiles.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * Author: loizenai.com 4 | */ 5 | 6 | $(document).ready(function() { 7 | 8 | /** 9 | * Upload single file to SpringBoot 10 | * at RestAPI: /api/upload/file/single 11 | */ 12 | $("#uploadSingleFileForm").submit(function(evt) { 13 | evt.preventDefault(); 14 | 15 | let formData = new FormData($(this)[0]); 16 | 17 | $.ajax({ 18 | url : '/api/file/upload', 19 | type : 'POST', 20 | data : formData, 21 | async : false, 22 | cache : false, 23 | contentType : false, 24 | enctype : 'multipart/form-data', 25 | processData : false, 26 | success : function(response) { 27 | $("#response").empty(); 28 | if(response.status !== "error"){ 29 | let displayInfo = response.filename + " : " + response.message + "
"; 30 | 31 | $("#response").append(displayInfo); 32 | // add some css 33 | $("#response").css("display", "block"); 34 | $("#response").css("background-color", "#e6e6ff"); 35 | $("#response").css("border", "solid 1px black"); 36 | $("#response").css("border-radius", "3px"); 37 | $("#response").css("margin", "10px"); 38 | $("#response").css("padding", "10px"); 39 | }else{ 40 | $("#response").css("display", "none"); 41 | let error = response.error; 42 | alert(error); 43 | } 44 | }, 45 | error: function(e){ 46 | alert("Fail! " + e); 47 | } 48 | }); 49 | 50 | return false; 51 | }); 52 | 53 | /** 54 | * Upload Multiple Files to SpringBoot RestAPI 55 | */ 56 | $("#uploadMultipleFilesForm").submit(function(evt) { 57 | evt.preventDefault(); 58 | 59 | let formData = new FormData($(this)[0]); 60 | 61 | $.ajax({ 62 | url : '/api/file/multiple/upload', 63 | type : 'POST', 64 | data : formData, 65 | async : false, 66 | cache : false, 67 | contentType : false, 68 | enctype : 'multipart/form-data', 69 | processData : false, 70 | success : function(response) { 71 | $("#responses").empty(); 72 | 73 | let displayInfo = "
    "; 74 | 75 | for(let i=0; i"); 82 | $("#responses").css("display", "block"); 83 | 84 | // add some css 85 | $("#responses").css("background-color", "#e6e6ff"); 86 | $("#responses").css("border", "solid 1px black"); 87 | $("#responses").css("border-radius", "3px"); 88 | $("#responses").css("margin", "10px"); 89 | $("#responses").css("padding", "10px"); 90 | }, 91 | error: function(e){ 92 | alert("Fail! " + e); 93 | } 94 | }); 95 | 96 | return false; 97 | }); 98 | }) -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | const db = require('./app/config/db.config.js'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | // force: true will drop the table if it already exists 9 | db.sequelize.sync({force: true}).then(() => { 10 | console.log('Drop and Resync with { force: true }'); 11 | }); 12 | 13 | let router = require('./app/routers/excel.router.js'); 14 | app.use(express.static('resources')); 15 | app.use('/', router); 16 | 17 | // Create a Server 18 | const server = app.listen(8080, function () { 19 | let host = server.address().address 20 | let port = server.address().port 21 | 22 | console.log("App listening at http://%s:%s", host, port); 23 | }) -------------------------------------------------------------------------------- /Nodejs-Upload-CSV-Files/views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Upload Download File Examples 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
    15 |
    16 |
    17 |

    Upload Single File

    18 |
    19 |
    20 | 21 | 23 |
    24 | 25 |
    26 | 28 |
    29 |
    30 |
    31 |
    32 |
    33 |

    Upload Multiple Files

    34 |
    35 |
    36 | 37 | 39 |
    40 | 41 |
    42 | 44 |
    45 | 46 |
    47 |
    48 |
    49 |
    50 | Download CSV File 51 |
    52 |
    53 |
    54 | 55 | -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/README.md: -------------------------------------------------------------------------------- 1 | Multer – Nodejs Upload/Download Multiple Files/Images to Server MySQL/PostgreSQL database – Sequelize + Ajax 2 | https://loizenai.com/nodejs-upload-download-multiple-files-images-to-server-mysql-postgresql-database-using-multer-sequelize-ajax/ 3 | 4 | Related posts: 5 | *** 6 | 1. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 7 | https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 8 | 9 | 2. Nodejs JWT Authentication Example – Express RestAPIs + JSON Web Token + BCryptjs + Sequelize + MySQL/PostgreSQL 10 | https://loizenai.com/nodejs-jwt-authentication-example-with-mysql-postgresql-database/ 11 | 12 | 3. Nodejs/Express CSV Upload Download to MySQL/PostgreSQL – Multer, Fast-CSV, Json2Csv, Sequelize 13 | https://loizenai.com/nodejs-express-csv-upload-download-to-mysql-postgresql-multer-fast-csv-json2csv-sequelize/ 14 | -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.files = require('../models/file.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/app/config/multer.config.js: -------------------------------------------------------------------------------- 1 | const multer = require('multer'); 2 | 3 | var storage = multer.memoryStorage() 4 | var upload = multer({storage: storage}); 5 | 6 | module.exports = upload; -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/app/controllers/file.controller.js: -------------------------------------------------------------------------------- 1 | var stream = require('stream'); 2 | var await = require('await') 3 | 4 | const db = require('../config/db.config.js'); 5 | const File = db.files; 6 | 7 | 8 | exports.uploadFile = (req, res) => { 9 | File.create({ 10 | type: req.file.mimetype, 11 | name: req.file.originalname, 12 | data: req.file.buffer 13 | }).then(file => { 14 | console.log(file); 15 | 16 | const result = { 17 | status: "ok", 18 | filename: req.file.originalname, 19 | message: "Upload Successfully!", 20 | downloadUrl: "http://localhost:8080/api/file/" + file.dataValues.id, 21 | } 22 | 23 | res.json(result); 24 | }).catch(err => { 25 | console.log(err); 26 | 27 | const result = { 28 | status: "error", 29 | error: err 30 | } 31 | res.json(result); 32 | }); 33 | } 34 | 35 | exports.uploadMultipleFiles = async (req, res) => { 36 | const messages = []; 37 | 38 | for (const file of req.files) { 39 | const uploadfile = await File.create({ 40 | type: file.mimetype, 41 | name: file.originalname, 42 | data: file.buffer 43 | }); 44 | 45 | // It will now wait for above Promise to be fulfilled and show the proper details 46 | console.log(uploadfile); 47 | 48 | if (!uploadfile){ 49 | const result = { 50 | status: "fail", 51 | filename: file.originalname, 52 | message: "Can NOT upload Successfully", 53 | } 54 | 55 | messages.push(result); 56 | } else { 57 | const result = { 58 | status: "ok", 59 | filename: file.originalname, 60 | message: "Upload Successfully!", 61 | downloadUrl: "http://localhost:8080/api/file/" + uploadfile.dataValues.id, 62 | } 63 | 64 | messages.push(result); 65 | } 66 | } 67 | 68 | return res.json(messages); 69 | } 70 | 71 | exports.listAllFiles = (req, res) => { 72 | File.findAll({attributes: ['id', 'name']}).then(files => { 73 | 74 | const fileInfo = []; 75 | 76 | console.log(files); 77 | 78 | for(let i=0; i { 87 | console.log(err); 88 | res.json({msg: 'Error', detail: err}); 89 | }); 90 | } 91 | 92 | exports.downloadFile = (req, res) => { 93 | File.findByPk(req.params.id).then(file => { 94 | var fileContents = Buffer.from(file.data, "base64"); 95 | var readStream = new stream.PassThrough(); 96 | readStream.end(fileContents); 97 | 98 | res.set('Content-disposition', 'attachment; filename=' + file.name); 99 | res.set('Content-Type', file.type); 100 | 101 | readStream.pipe(res); 102 | }).catch(err => { 103 | console.log(err); 104 | res.json({msg: 'Error', detail: err}); 105 | }); 106 | } -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/app/models/file.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const File = sequelize.define('file', { 3 | type: { 4 | type: Sequelize.STRING 5 | }, 6 | name: { 7 | type: Sequelize.STRING 8 | }, 9 | data: { 10 | type: Sequelize.BLOB('long') 11 | } 12 | }); 13 | 14 | return File; 15 | } -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/app/routers/file.router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | let upload = require('../config/multer.config.js'); 4 | 5 | const fileWorker = require('../controllers/file.controller.js'); 6 | 7 | let path = __basedir + '/views/'; 8 | 9 | router.get('/', (req,res) => { 10 | res.sendFile(path + "index.html"); 11 | }); 12 | 13 | router.post('/api/file/upload', upload.single("file"), fileWorker.uploadFile); 14 | router.post('/api/file/multiple/upload', upload.array('files', 4), fileWorker.uploadMultipleFiles); 15 | 16 | router.get('/api/file/info', fileWorker.listAllFiles); 17 | 18 | router.get('/api/file/:id', fileWorker.downloadFile); 19 | 20 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-upload-download-files", 3 | "version": "1.0.0", 4 | "description": "Nodejs Upload Download Files/Images to MySQL/PostgreSQL database", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "Nodejs" 11 | ], 12 | "author": "https:/loizenai.com", 13 | "license": "ISC", 14 | "dependencies": { 15 | "await": "^0.2.6", 16 | "express": "^4.17.1", 17 | "multer": "^1.4.2", 18 | "mysql2": "^2.1.0", 19 | "sequelize": "^5.21.12" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/resources/static/js/uploaddownloadfiles.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * Author: loizenai.com 4 | */ 5 | 6 | $(document).ready(function() { 7 | 8 | /** 9 | * Upload single file to SpringBoot 10 | * at RestAPI: /api/upload/file/single 11 | */ 12 | $("#uploadSingleFileForm").submit(function(evt) { 13 | evt.preventDefault(); 14 | 15 | let formData = new FormData($(this)[0]); 16 | 17 | $.ajax({ 18 | url : '/api/file/upload', 19 | type : 'POST', 20 | data : formData, 21 | async : false, 22 | cache : false, 23 | contentType : false, 24 | enctype : 'multipart/form-data', 25 | processData : false, 26 | success : function(response) { 27 | $("#response").empty(); 28 | if(response.status !== "error"){ 29 | let displayInfo = response.filename + " : " + response.message + "
    "; 30 | 31 | $("#response").append(displayInfo); 32 | 33 | let downloadLink = response.downloadUrl; 34 | let downloadAt = "    -> Download File: " 35 | + "" + downloadLink + ""; 36 | 37 | $("#response").append(downloadAt); 38 | 39 | // add some css 40 | $("#response").css("display", "block"); 41 | $("#response").css("background-color", "#e6e6ff"); 42 | $("#response").css("border", "solid 1px black"); 43 | $("#response").css("border-radius", "3px"); 44 | $("#response").css("margin", "10px"); 45 | $("#response").css("padding", "10px"); 46 | }else{ 47 | $("#response").css("display", "none"); 48 | let error = response.error; 49 | alert(error); 50 | } 51 | }, 52 | error: function(e){ 53 | alert("Fail! " + e); 54 | } 55 | }); 56 | 57 | return false; 58 | }); 59 | 60 | 61 | /** 62 | * Upload Multiple Files to SpringBoot RestAPI 63 | */ 64 | $("#uploadMultipleFilesForm").submit(function(evt) { 65 | evt.preventDefault(); 66 | 67 | let formData = new FormData($(this)[0]); 68 | 69 | $.ajax({ 70 | url : '/api/file/multiple/upload', 71 | type : 'POST', 72 | data : formData, 73 | async : false, 74 | cache : false, 75 | contentType : false, 76 | enctype : 'multipart/form-data', 77 | processData : false, 78 | success : function(response) { 79 | $("#responses").empty(); 80 | 81 | let displayInfo = "
      "; 82 | 83 | for(let i=0; i" + response[i].downloadUrl + ""; 90 | 91 | displayInfo += "
      " + downloadAt; 92 | } 93 | 94 | displayInfo += ""; 95 | } 96 | $("#responses").append(displayInfo + "
    "); 97 | $("#responses").css("display", "block"); 98 | 99 | // add some css 100 | $("#responses").css("background-color", "#e6e6ff"); 101 | $("#responses").css("border", "solid 1px black"); 102 | $("#responses").css("border-radius", "3px"); 103 | $("#responses").css("margin", "10px"); 104 | $("#responses").css("padding", "10px"); 105 | }, 106 | error: function(e){ 107 | alert("Fail! " + e); 108 | } 109 | }); 110 | 111 | return false; 112 | }); 113 | 114 | /** 115 | * Get all uploaded files and download-links 116 | */ 117 | $( "#btnGetFiles").click(function() { 118 | $.get('/api/file/info', function (response, textStatus, jqXHR) { // success callback 119 | 120 | let files = ""; 130 | 131 | console.log(files); 132 | 133 | $("#allfiles").append(files); 134 | 135 | console.log("--end--"); 136 | 137 | // add some css 138 | $("#uploadfiles").css("background-color", "#e6e6ff"); 139 | $("#uploadfiles").css("border", "solid 1px black"); 140 | $("#uploadfiles").css("border-radius", "3px"); 141 | $("#uploadfiles").css("margin", "10px"); 142 | $("#uploadfiles").css("padding", "10px"); 143 | }); 144 | }); 145 | }) -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | global.__basedir = __dirname; 5 | 6 | const db = require('./app/config/db.config.js'); 7 | 8 | // force: true will drop the table if it already exists 9 | db.sequelize.sync({force: true}).then(() => { 10 | console.log('Drop and Resync with { force: true }'); 11 | }); 12 | 13 | let router = require('./app/routers/file.router.js'); 14 | app.use(express.static('resources')); 15 | app.use('/', router); 16 | 17 | // Create a Server 18 | const server = app.listen(8080, function () { 19 | 20 | let host = server.address().address 21 | let port = server.address().port 22 | 23 | console.log("App listening at http://%s:%s", host, port); 24 | }) -------------------------------------------------------------------------------- /Nodejs-Upload-Download-Files/views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Upload Download File Examples 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
    15 |
    16 |
    17 |

    Upload Single File

    18 |
    19 |
    20 | 21 | 23 |
    24 | 25 |
    26 | 28 |
    29 |
    30 |
    31 |
    32 |
    33 |

    Upload Multiple Files

    34 |
    35 |
    36 | 37 | 39 |
    40 | 41 |
    42 | 44 |
    45 | 46 |
    47 |
    48 |
    49 |
    50 | 51 |
    52 |
    53 |
    54 |
    55 |
    56 | 57 | -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/README.md: -------------------------------------------------------------------------------- 1 | Nodejs RestAPIs Upload Download Multiple Excel Files to MySQL/PostgreSQL – Multer, Sequelize ORM, Exceljs, Read-excel-file 2 | https://loizenai.com/nodejs-restapis-upload-download-multiple-excel-files-to-mysql-postgresql/ 3 | 4 | Related posts: 5 | 1. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 6 | https://loizenai.com/angular-nodejs-fullstack-crud-application-with-mysql-postgresql-angular-10-9-8-httpclient-client-nodejs-express-sequelize-orm/ 7 | 8 | 2. Nodejs/Express CSV Upload Download to MySQL/PostgreSQL – Multer, Fast-CSV, Json2Csv, Sequelize 9 | https://loizenai.com/nodejs-express-csv-upload-download-to-mysql-postgresql-multer-fast-csv-json2csv-sequelize/ 10 | 11 | 3. Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request 12 | https://loizenai.com/build-nodejs-crud-application-with-mysql-postgresql-express-restapis-ajax-post-get-put-delete-request/ 13 | -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.Customer = require('../models/customer.model.js')(sequelize, Sequelize); 23 | 24 | module.exports = db; -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/app/config/multer.config.js: -------------------------------------------------------------------------------- 1 | const multer = require('multer'); 2 | 3 | const storage = multer.diskStorage({ 4 | destination: (req, file, cb) => { 5 | cb(null, __basedir + '/uploads/') 6 | }, 7 | filename: (req, file, cb) => { 8 | cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname) 9 | } 10 | }); 11 | 12 | const upload = multer({storage: storage}); 13 | 14 | module.exports = upload; -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/app/models/customer.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Customer = sequelize.define('customer', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | autoIncrement: true, 6 | primaryKey: true 7 | }, 8 | name: { 9 | type: Sequelize.STRING 10 | }, 11 | address: { 12 | type: Sequelize.STRING 13 | }, 14 | age: { 15 | type: Sequelize.INTEGER 16 | } 17 | }); 18 | 19 | return Customer; 20 | } -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/app/routers/excel.router.js: -------------------------------------------------------------------------------- 1 | let express = require('express'); 2 | let router = express.Router(); 3 | let upload = require('../config/multer.config.js'); 4 | 5 | const excelWorker = require('../controllers/excel.controller.js'); 6 | 7 | let path = __basedir + '/views/'; 8 | 9 | router.get('/', (req,res) => { 10 | console.log("__basedir" + __basedir); 11 | res.sendFile(path + "index.html"); 12 | }); 13 | 14 | router.post('/api/file/upload', upload.single("file"), excelWorker.uploadFile); 15 | router.post('/api/file/multiple/upload', upload.array('files', 4), excelWorker.uploadMultipleFiles); 16 | 17 | router.get('/api/file', excelWorker.downloadFile); 18 | 19 | module.exports = router; -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-upload-excel-files", 3 | "version": "1.0.0", 4 | "description": "Nodejs Upload/Extract and Download/Import Excels files to MySQL", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "nodejs", 11 | "mysql", 12 | "upload_excel_files", 13 | "download_excel_file", 14 | "export_excel_file", 15 | "import_excel_file" 16 | ], 17 | "author": "https://loizenai.com", 18 | "license": "ISC", 19 | "dependencies": { 20 | "await": "^0.2.6", 21 | "exceljs": "^4.0.1", 22 | "express": "^4.17.1", 23 | "multer": "^1.4.2", 24 | "mysql2": "^2.1.0", 25 | "read-excel-file": "^4.0.6", 26 | "sequelize": "^5.21.13" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/resources/static/js/uploaddownloadfiles.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright by https://loizenai.com 3 | * Author: loizenai.com 4 | */ 5 | 6 | $(document).ready(function() { 7 | 8 | /** 9 | * Upload single file to SpringBoot 10 | * at RestAPI: /api/upload/file/single 11 | */ 12 | $("#uploadSingleFileForm").submit(function(evt) { 13 | evt.preventDefault(); 14 | 15 | let formData = new FormData($(this)[0]); 16 | 17 | $.ajax({ 18 | url : '/api/file/upload', 19 | type : 'POST', 20 | data : formData, 21 | async : false, 22 | cache : false, 23 | contentType : false, 24 | enctype : 'multipart/form-data', 25 | processData : false, 26 | success : function(response) { 27 | $("#response").empty(); 28 | if(response.status !== "error"){ 29 | let displayInfo = response.filename + " : " + response.message + "
    "; 30 | 31 | $("#response").append(displayInfo); 32 | // add some css 33 | $("#response").css("display", "block"); 34 | $("#response").css("background-color", "#e6e6ff"); 35 | $("#response").css("border", "solid 1px black"); 36 | $("#response").css("border-radius", "3px"); 37 | $("#response").css("margin", "10px"); 38 | $("#response").css("padding", "10px"); 39 | }else{ 40 | $("#response").css("display", "none"); 41 | let error = response.error; 42 | alert(error); 43 | } 44 | }, 45 | error: function(e){ 46 | alert("Fail! " + e); 47 | } 48 | }); 49 | 50 | return false; 51 | }); 52 | 53 | /** 54 | * Upload Multiple Files to SpringBoot RestAPI 55 | */ 56 | $("#uploadMultipleFilesForm").submit(function(evt) { 57 | evt.preventDefault(); 58 | 59 | let formData = new FormData($(this)[0]); 60 | 61 | $.ajax({ 62 | url : '/api/file/multiple/upload', 63 | type : 'POST', 64 | data : formData, 65 | async : false, 66 | cache : false, 67 | contentType : false, 68 | enctype : 'multipart/form-data', 69 | processData : false, 70 | success : function(response) { 71 | $("#responses").empty(); 72 | 73 | let displayInfo = "
      "; 74 | 75 | for(let i=0; i"); 82 | $("#responses").css("display", "block"); 83 | 84 | // add some css 85 | $("#responses").css("background-color", "#e6e6ff"); 86 | $("#responses").css("border", "solid 1px black"); 87 | $("#responses").css("border-radius", "3px"); 88 | $("#responses").css("margin", "10px"); 89 | $("#responses").css("padding", "10px"); 90 | }, 91 | error: function(e){ 92 | alert("Fail! " + e); 93 | } 94 | }); 95 | 96 | return false; 97 | }); 98 | }) -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const app = express(); 3 | 4 | const db = require('./app/config/db.config.js'); 5 | 6 | global.__basedir = __dirname; 7 | 8 | // force: true will drop the table if it already exists 9 | db.sequelize.sync({force: true}).then(() => { 10 | console.log('Drop and Resync with { force: true }'); 11 | }); 12 | 13 | let router = require('./app/routers/excel.router.js'); 14 | app.use(express.static('resources')); 15 | app.use('/', router); 16 | 17 | // Create a Server 18 | const server = app.listen(8080, function () { 19 | let host = server.address().address 20 | let port = server.address().port 21 | 22 | console.log("App listening at http://%s:%s", host, port); 23 | }) -------------------------------------------------------------------------------- /Nodejs-Upload-Excel-Files/views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Upload Download File Examples 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
      15 |
      16 |
      17 |

      Upload Single File

      18 |
      19 |
      20 | 21 | 23 |
      24 | 25 |
      26 | 28 |
      29 |
      30 |
      31 |
      32 |
      33 |

      Upload Multiple Files

      34 |
      35 |
      36 | 37 | 39 |
      40 | 41 |
      42 | 44 |
      45 | 46 |
      47 |
      48 |
      49 | 52 |
      53 |
      54 | 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nodejs-Tutorials 2 | 3 | Article List: 4 | ------------------- 5 | 1. Nodejs/Express CSV Upload Download to MySQL/PostgreSQL – Multer, Fast-CSV, Json2Csv, Sequelize 6 | https://ozenero.com/nodejs-tutorial 7 | 8 | 9 | 2. Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request 10 | https://ozenero.com/react-js-crud-web-api-nodejs-mysql 11 | 12 | 3. Angular Nodejs Fullstack CRUD Application with MySQL/PostgreSQL – Angular 10-9-8 HttpClient + Nodejs Express, Sequelize ORM 13 | https://ozenero.com/angular-client-side-pagination-with-nodejs-mysql 14 | 15 | 4. Nodejs RestAPIs Upload Download Multiple Excel Files to MySQL/PostgreSQL – Multer, Sequelize ORM, Exceljs, Read-excel-file 16 | https://ozenero.com/nodejs-express-restapi-upload-import-excel-file-to-mysql-using-read-excel-file-multer 17 | 18 | 5. Multer – Nodejs Upload/Download Multiple Files/Images to Server MySQL/PostgreSQL database – Sequelize + Ajax 19 | https://ozenero.com/nodejs-express-upload-download-multiparfile-to-mysql-multer-sequelize-jquery-ajax-bootstrap 20 | 21 | 6. Tutorial Nodejs Express RestAPIs MySQL with Sequelize Queries Examples 22 | https://ozenero.com/sequelize-orm-build-crud-restapis-with-nodejs-express-sequelize-mysql 23 | 24 | 7. Nodejs MySQL Pagination Filtering Sorting Tutorial – Stack: Express RestAPIs + Sequelize ORM + MySQL database Examples 25 | https://ozenero.com/angular-client-side-pagination-with-nodejs-mysql 26 | 27 | 8. Angular 10 Nodejs Pagination RestAPIs + Filtering Sorting Example – Fullstack: Angular + Nodejs RestAPIs+ MySQL Tutorial 28 | https://ozenero.com/angular-client-side-pagination-with-nodejs-mysql 29 | 30 | 9. Ajax Pagination Node.js MySQL RestAPIs Example – Client Side Pagination in Node.js Tutorial 31 | https://ozenero.com/spring-boot-angular-11-pagination-example 32 | 33 | 10. Token Based Authentication in Node.js using JWT (JSON Web Tokens) + MySQL Example 34 | https://ozenero.com/nodejs-jwt-authentication-nodejs-express-restapis-json-web-token-bcryptjs-sequelize-mysql 35 | 36 | 11. Angular 10 + Nodejs JWT Token Based Authentication with MySQL Example - Express RestAPIs + JWT + BCryptjs + Sequelize 37 | https://ozenero.com/nodejs-jwt-authentication-nodejs-express-restapis-json-web-token-bcryptjs-sequelize-mysql 38 | -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/README.md: -------------------------------------------------------------------------------- 1 | Article: Token Based Authentication in Node.js using JWT (JSON Web Tokens) + MySQL Example 2 | https://loizenai.com/nodejs-token-based-authentication-jwt-json-web-tokens-authentication-mysql-example/ 3 | 4 | Related posts: 5 | 6 | Angular 10 Nodejs JWT Token Based Authentication Example 7 | 1. https://loizenai.com/angular-nodejs-jwt-authentication-examples-tutorials/ 8 | 9 | SpringBoot JWT Token Based Authentication Example 10 | 2. https://loizenai.com/spring-boot-security-jwt-authentication-example-mysql-postgresql-spring-jpa-restapis/ 11 | 12 | Angular 10 SpringBoot Token Based JWT Authentication Example 13 | 3. https://loizenai.com/angular-spring-boot-jwt-authentication-example-angular-6-8-9-spring-security-mysql-postgresql/ 14 | -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/config/config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'secret': 'loizenai-super-secret-key', 3 | ROLEs: ['USER', 'ADMIN', 'PM'] 4 | }; -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/config/db.config.js: -------------------------------------------------------------------------------- 1 | const env = require('./env.js'); 2 | 3 | const Sequelize = require('sequelize'); 4 | const sequelize = new Sequelize(env.database, env.username, env.password, { 5 | host: env.host, 6 | dialect: env.dialect, 7 | operatorsAliases: false, 8 | 9 | pool: { 10 | max: env.max, 11 | min: env.pool.min, 12 | acquire: env.pool.acquire, 13 | idle: env.pool.idle 14 | } 15 | }); 16 | 17 | const db = {}; 18 | 19 | db.Sequelize = Sequelize; 20 | db.sequelize = sequelize; 21 | 22 | db.user = require('../model/user.model.js')(sequelize, Sequelize); 23 | db.role = require('../model/role.model.js')(sequelize, Sequelize); 24 | 25 | db.role.belongsToMany(db.user, { through: 'user_roles', foreignKey: 'roleId', otherKey: 'userId'}); 26 | db.user.belongsToMany(db.role, { through: 'user_roles', foreignKey: 'userId', otherKey: 'roleId'}); 27 | 28 | module.exports = db; -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/config/env.js: -------------------------------------------------------------------------------- 1 | const env = { 2 | database: 'loizenaidb', 3 | username: 'root', 4 | password: '12345', 5 | host: 'localhost', 6 | dialect: 'mysql', 7 | pool: { 8 | max: 5, 9 | min: 0, 10 | acquire: 30000, 11 | idle: 10000 12 | } 13 | }; 14 | 15 | module.exports = env; 16 | -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/controller/controller.js: -------------------------------------------------------------------------------- 1 | const db = require('../config/db.config.js'); 2 | const config = require('../config/config.js'); 3 | const User = db.user; 4 | const Role = db.role; 5 | 6 | const Op = db.Sequelize.Op; 7 | 8 | var jwt = require('jsonwebtoken'); 9 | var bcrypt = require('bcryptjs'); 10 | 11 | exports.signup = (req, res) => { 12 | // Save User to Database 13 | console.log("Processing func -> SignUp"); 14 | 15 | User.create({ 16 | name: req.body.name, 17 | username: req.body.username, 18 | email: req.body.email, 19 | password: bcrypt.hashSync(req.body.password, 8) 20 | }).then(user => { 21 | Role.findAll({ 22 | where: { 23 | name: { 24 | [Op.or]: req.body.roles 25 | } 26 | } 27 | }).then(roles => { 28 | user.setRoles(roles).then(() => { 29 | res.send("User registered successfully!"); 30 | }); 31 | }).catch(err => { 32 | res.status(500).send("Error -> " + err); 33 | }); 34 | }).catch(err => { 35 | res.status(500).send("Fail! Error -> " + err); 36 | }) 37 | } 38 | 39 | exports.signin = (req, res) => { 40 | console.log("Sign-In"); 41 | 42 | User.findOne({ 43 | where: { 44 | username: req.body.username 45 | } 46 | }).then(user => { 47 | if (!user) { 48 | return res.status(404).send('User Not Found.'); 49 | } 50 | 51 | var passwordIsValid = bcrypt.compareSync(req.body.password, user.password); 52 | if (!passwordIsValid) { 53 | return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" }); 54 | } 55 | 56 | var token = jwt.sign({ id: user.id }, config.secret, { 57 | expiresIn: 86400 // expires in 24 hours 58 | }); 59 | 60 | res.status(200).send({ auth: true, accessToken: token }); 61 | 62 | }).catch(err => { 63 | res.status(500).send('Error -> ' + err); 64 | }); 65 | } 66 | 67 | exports.userContent = (req, res) => { 68 | User.findOne({ 69 | where: {id: req.userId}, 70 | attributes: ['name', 'username', 'email'], 71 | include: [{ 72 | model: Role, 73 | attributes: ['id', 'name'], 74 | through: { 75 | attributes: ['userId', 'roleId'], 76 | } 77 | }] 78 | }).then(user => { 79 | res.status(200).json({ 80 | "description": "User Content Page", 81 | "user": user 82 | }); 83 | }).catch(err => { 84 | res.status(500).json({ 85 | "description": "Can not access User Page", 86 | "error": err 87 | }); 88 | }) 89 | } 90 | 91 | exports.adminBoard = (req, res) => { 92 | User.findOne({ 93 | where: {id: req.userId}, 94 | attributes: ['name', 'username', 'email'], 95 | include: [{ 96 | model: Role, 97 | attributes: ['id', 'name'], 98 | through: { 99 | attributes: ['userId', 'roleId'], 100 | } 101 | }] 102 | }).then(user => { 103 | res.status(200).json({ 104 | "description": "Admin Board", 105 | "user": user 106 | }); 107 | }).catch(err => { 108 | res.status(500).json({ 109 | "description": "Can not access Admin Board", 110 | "error": err 111 | }); 112 | }) 113 | } 114 | 115 | exports.managementBoard = (req, res) => { 116 | User.findOne({ 117 | where: {id: req.userId}, 118 | attributes: ['name', 'username', 'email'], 119 | include: [{ 120 | model: Role, 121 | attributes: ['id', 'name'], 122 | through: { 123 | attributes: ['userId', 'roleId'], 124 | } 125 | }] 126 | }).then(user => { 127 | res.status(200).json({ 128 | "description": "Management Board", 129 | "user": user 130 | }); 131 | }).catch(err => { 132 | res.status(500).json({ 133 | "description": "Can not access Management Board", 134 | "error": err 135 | }); 136 | }) 137 | } -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/model/role.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const Role = sequelize.define('roles', { 3 | id: { 4 | type: Sequelize.INTEGER, 5 | primaryKey: true 6 | }, 7 | name: { 8 | type: Sequelize.STRING 9 | } 10 | }); 11 | 12 | return Role; 13 | } -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/model/user.model.js: -------------------------------------------------------------------------------- 1 | module.exports = (sequelize, Sequelize) => { 2 | const User = sequelize.define('users', { 3 | name: { 4 | type: Sequelize.STRING 5 | }, 6 | username: { 7 | type: Sequelize.STRING 8 | }, 9 | email: { 10 | type: Sequelize.STRING 11 | }, 12 | password: { 13 | type: Sequelize.STRING 14 | } 15 | }); 16 | 17 | return User; 18 | } -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/router/router.js: -------------------------------------------------------------------------------- 1 | const verifySignUp = require('./verifySignUp'); 2 | const authJwt = require('./verifyJwtToken'); 3 | 4 | module.exports = function(app) { 5 | 6 | const controller = require('../controller/controller.js'); 7 | 8 | app.post('/api/auth/signup', [verifySignUp.checkDuplicateUserNameOrEmail, verifySignUp.checkRolesExisted], controller.signup); 9 | 10 | app.post('/api/auth/signin', controller.signin); 11 | 12 | app.get('/api/test/user', [authJwt.verifyToken], controller.userContent); 13 | 14 | app.get('/api/test/pm', [authJwt.verifyToken, authJwt.isPmOrAdmin], controller.managementBoard); 15 | 16 | app.get('/api/test/admin', [authJwt.verifyToken, authJwt.isAdmin], controller.adminBoard); 17 | } -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/app/router/verifyJwtToken.js: -------------------------------------------------------------------------------- 1 | const jwt = require('jsonwebtoken'); 2 | const config = require('../config/config.js'); 3 | const db = require('../config/db.config.js'); 4 | const Role = db.role; 5 | const User = db.user; 6 | 7 | verifyToken = (req, res, next) => { 8 | let token = req.headers['x-access-token']; 9 | 10 | if (!token){ 11 | return res.status(403).send({ 12 | auth: false, message: 'No token provided.' 13 | }); 14 | } 15 | 16 | jwt.verify(token, config.secret, (err, decoded) => { 17 | if (err){ 18 | return res.status(500).send({ 19 | auth: false, 20 | message: 'Fail to Authentication. Error -> ' + err 21 | }); 22 | } 23 | req.userId = decoded.id; 24 | next(); 25 | }); 26 | } 27 | 28 | isAdmin = (req, res, next) => { 29 | let token = req.headers['x-access-token']; 30 | 31 | User.findByPk(req.userId) 32 | .then(user => { 33 | user.getRoles().then(roles => { 34 | for(let i=0; i { 49 | let token = req.headers['x-access-token']; 50 | 51 | User.findByPk(req.userId) 52 | .then(user => { 53 | user.getRoles().then(roles => { 54 | for(let i=0; i { 8 | // -> Check Username is already in use 9 | User.findOne({ 10 | where: { 11 | username: req.body.username 12 | } 13 | }).then(user => { 14 | if(user){ 15 | res.status(400).send("Fail -> Username is already taken!"); 16 | return; 17 | } 18 | 19 | // -> Check Email is already in use 20 | User.findOne({ 21 | where: { 22 | email: req.body.email 23 | } 24 | }).then(user => { 25 | if(user){ 26 | res.status(400).send("Fail -> Email is already in use!"); 27 | return; 28 | } 29 | 30 | next(); 31 | }); 32 | }); 33 | } 34 | 35 | checkRolesExisted = (req, res, next) => { 36 | for(let i=0; i Does NOT exist Role = " + req.body.roles[i]); 39 | return; 40 | } 41 | } 42 | next(); 43 | } 44 | 45 | const signUpVerify = {}; 46 | signUpVerify.checkDuplicateUserNameOrEmail = checkDuplicateUserNameOrEmail; 47 | signUpVerify.checkRolesExisted = checkRolesExisted; 48 | 49 | module.exports = signUpVerify; -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-jwt-auth", 3 | "version": "1.0.0", 4 | "description": "Build Nodejs JWT Authentication RestAPIs ", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "nodejs", 11 | "jwt", 12 | "authentication", 13 | "restapis" 14 | ], 15 | "author": "https://loizenai.com", 16 | "license": "ISC", 17 | "dependencies": { 18 | "bcryptjs": "^2.4.3", 19 | "express": "^4.17.1", 20 | "jsonwebtoken": "^8.5.1", 21 | "mysql2": "^2.1.0", 22 | "sequelize": "^5.21.12" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Token Based Authentication in Nodejs using JWT(Json Web Token) Example/server.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | app.use(bodyParser.json()) 5 | 6 | require('./app/router/router.js')(app); 7 | 8 | const db = require('./app/config/db.config.js'); 9 | 10 | const Role = db.role; 11 | 12 | // force: true will drop the table if it already exists 13 | db.sequelize.sync({force: true}).then(() => { 14 | console.log('Drop and Resync with { force: true }'); 15 | initial(); 16 | }); 17 | 18 | //require('./app/route/project.route.js')(app); 19 | 20 | // Create a Server 21 | var server = app.listen(8080, function () { 22 | 23 | var host = server.address().address 24 | var port = server.address().port 25 | 26 | console.log("App listening at http://%s:%s", host, port) 27 | }) 28 | 29 | 30 | function initial(){ 31 | Role.create({ 32 | id: 1, 33 | name: "USER" 34 | }); 35 | 36 | Role.create({ 37 | id: 2, 38 | name: "ADMIN" 39 | }); 40 | 41 | Role.create({ 42 | id: 3, 43 | name: "PM" 44 | }); 45 | } --------------------------------------------------------------------------------