REST API with Node JS using MySQL

This is a very beginning of nodeJS who want to learn from scratch. Below are the steps to create an application with Node JS using Express JS.

Express JS is a web application framework for Node JS.

Let’s begin.

  1. Verify that Is node js installed or not using below command.
nodejs -v

It will display version of node js installed in your system, If it not displaying version then you need to install node js in your system.

Install NodeJS using below command

sudo apt-get update
sudo apt-get install nodejs
nodejs -v

2. You have to verify that is NPM (Node Package Manager) available in your system or not using below command.

npm -v

It will display version of NPM in your system, If it is not displaying version then you need to install NPM in your system.

Install NPM using below command.

sudo apt-get update
sudo apt-get install npm
npm -v

3. It’s good to go now. Go to your prefered work directory and create project-directory and go inside project-directory.

sudo mkdir <project-directory>
cd <project-directory>

4. Initiate the Node JS using npm init, It will create package.json file in your project-directory.

package.json file will contain all the project related information and dependency packages.

npm init

5. Now you have to install dependencies in your project. Some of the dependencies are common for all. You can add/remove dependencies with your requirements.

npm install --save express
npm install --save body-parser
npm install --save bcrypt
npm install --save express-validator
npm install --save jsonwebtoken
npm install --save mysql
npm install --save util
npm install --save fs

You can add some devDependencies also

npm install --save-dev nodemon

It will create one directory named node_modules which contain all the dependencies.

6. Create entry point of the project. Create an index.js file in the root of the project-directory

touch index.js

7. Import the dependencies into index.js file

express         = module.exports = require('express');
bodyParser = module.exports = require('body-parser');
expressValidator= module.exports = require('express-validator');
fileUpload = module.exports = require('express-fileupload');
jwt = module.exports = require('jsonwebtoken');
fs = module.exports = require('fs');
nodemailer = module.exports = require('nodemailer');
let routes = require('./routes'); //path to the routes.js
connection = require('./config/database') //path to the config/database.js
logger = require('./logs'); //path to the logs/index.js

module.exports will export these package across other files.

Set the port number for our application in which all request will be serve. This application will be run on 8080 port of HTTP.

var port = process.env.PORT || 8080;

8. create an instance of express and use dependencies in the app.

var app = express();
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(expressValidator());


app.use('/v1.0',route); //Set prefix in route v1.0; redirect the
routes to the routes.js file;
//create app listner
app.listen(port, console.log('Application is running at ' + port));
//export the instance of express
module.exports = app;

9. Create a routes.js file in the root of project-directory

touch routes.js

10. Create an instance of express routes

var routes = require('express').Router(); //create instance of express routes
var userRoute = require('./routes/user.route'); //path to the routes/user.routes.js 
routes.use('/user',userRoute); //redirect user's routes
module.exports = routes; //export express routes

11. Create user.route.js file inside routes/ directory

mkdir routes
cd routes
touch user.route.js

12. user.route.js file

var routes = require('express').Router(); //create instance of express routes
var userValidator = require('./../validation/user.validation'); //path to the validation/user.validation.js
var userController = require('./../controller/user.controller'); //path to the controller/user.controller.js

//create the routes
routes.post('/<your-route-name>',
[
userValidator.validateAddUser,
//function that validate request using express-validator
userValidator.checkValidationResult,
],
userController.createUser
//controller function that actually perform business logic
);

13. Create user.validation.js file inside validation/ directory

mkdir validation
cd validation
touch user.validation.js

14. user.validation.js file

var response = require('./../general/MyResponse'); //common function for every http response inside general folder
var messages = require('./../general/messages'); //common files inside general folder for each error message in app
//create instance of express-validator
const {check,validationResult} = require('express-validator/check');
const {matchedData, sanitize} = require('express-validator/filter');
module.exports.checkValidationResult = checkValidationResult; 
//function that validate express-validator resultsfunction checkValidationResult(req, res, next) {
var result = validationResult(req)
if (!result.isEmpty()) {
response.createResponse(res, 400,result.array()[0].msg,{}, {});
//response.createResponse is a method of general/MyResponse
} else {
next();
//go ahead if request is valid
}
}
//function that actually validate request
module.exports.validateAddUser = [
check('email').isLength({min: 1}).withMessage(messages.EMAIL_REQUIRED).isEmail().withMessage(messages.INVALID_EMAIL),
check('password').isLength({ min: 1 }).withMessage(messages.PASSWORD_REQUIRED),
check('confirmPassword').isLength({ min: 1 }).withMessage(messages.CONFIRM_PASSWORD_REQUIRED).isLength({max:6}).withMessage(messages.CONFIRM_PASSWORD_MAX_LENGTH)
.custom((value, {req}) => {
if (value !== req.body.newPassword) {
throw new Error(messages.PASSWOD_AND_CONFIRM_PASSWORD_SAME)
} else {
return true;
}
}),
];

15. Create user.controller.js file inside controller/ directory

mkdir controller
cd controller
touch user.controller.js

16. user.controller.js file

Required necessary dependency

var response = require('./../general/MyResponse');
var messages = require('./../general/messages');
var logger = require('./../logs');
var config = require('./../config/config');
module.exports = {
createUser: async (req, res) => {
//create user
var query = "INSERT INTO users (" +
"email, password ) " +
"VALUES (?, ?)";

var data = [req.body.email, req.body.password]
try{
var user = connection.query(query, data);
} catch (err) {
console.log("Error occurred : ", err.message);
logger.error("Error", err.message);
response.createResponse(res,500,err.message,{},{});
}
response.createResponse(res, 200, messages.USER_CREATED_SUCCESS, {}, {});
},
};

17. create config folder for configuration and database connections.

sudo mkdir config
cd config
touch config.js
touch database.js

18. config.js file

set all global variables inside this file

module.exports = {
superSecret : 'xyz@123',
bcryptSalt : 10,
dbHost : 'localhost',
dbName : 'node-js-training',
dbUser : 'root',
dbPassword : 'root',
EMAIL_USERNAME : 'abcd@xxx.com',
EMAIL_PASSWORD : 'xxxxx',
};

19. database.js file

var mysql = require('mysql'); //require mysql
var config = require('./config'); //import config file for DB information
var util = require('util');
//create pool connection of MySQL
var pool = mysql.createPool({
connectionLimit: 100,
host: config.dbHost,
user: config.dbUser,
password: config.dbPassword,
database: config.dbName
});

pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.log('Database connection was closed.');
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.log('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.log('Database connection was refused.');
}
if (connection) connection.release();
return
}
});

pool.query = util.promisify(pool.query); // Magic happens here.

module.exports = pool; //export the pool variable for globally use

20. Create General files for common methods and error messages

sudo mkdir general
cd general
touch messages.js
touch MyResponse.js

21. messages.js file

module.exports = {
//Response messages
SOMETHING_WRONG : 'Something went wrong. Please try later.',
SERVER_ERR : 'Internal server error. Please try later.',
USER_CREATED_SUCCESS : 'User created successfully',
};

22. MyResponse.js file

exports.createResponse = createResponse; //export function for globally use
// Function for create response
function createResponse(res, status, message, data, pager)
{
return res.status(status).send({
'status' : status,
'message' : message,
'payload' : data,
'pager' : pager
});
}

23. That’s it; Now you can index.js file directly or you can run it via nodemon also

node index.js

Or

nodemon
run application using nodemon
API response in JSON
Like what you read? Give Ketav Chotaliya a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.