WEB APPLICATION IN NODEJS USING EXPRESS: PART 1

Lydia Tosin
4 min readNov 24, 2020

INTRODUCTION
This article uses Express Js for handling Hypertext Transfer Protocol(HTTP) requests and MYSQL for storing data. Node Js is a platform used for building server side application using Javascript. Express is a flexible Node Js web application framework and provides a set of robust features for web and mobile applications.Developers do not need to build everything from scratch. Our first focus is ExpressJs which is one of the most used packages by developers build web APIs. Lastly, we focus on sequelize which is used to simplify the communication between NodeJs and MYSQL.

REQUIREMENTS

  • Basic Javascript Knowledge
  • Install Node.Js
  • Install NPM
  • Install Express
  • Install MYSQL Server
  • Install XAMPP
  • Sequelize
  • Visual Studio(VS) Code or any other editor

    CREATING PROJECT USING EXPRESS GENERATOR

STEP 1

Open command prompt.
STEP 2

Create a folder for the node project in the location of your choice. Navigate to the folder, and then type
Make directory to the name of the folder

$ mkdir fileName$ cd fileName $ code . 

to take you to the code editor

STEP 3

We run

$ npx express-generator

In order to generate the express server.
We can install express globally for our projects

$ npm install -g express-generator

The folders above are generated by express. The project is created with series of directories as javascripts, stylesheets, routes, views and with files as package.json, app.js and few other files. This also specifies the next step to be executed (the command to install the dependencies)

STEP 4

$ npm install

This help us install dependencies. Lets view the package.json file that is created. All the dependencies needed for the project is added here automatically. A directory with the name node_modules is created in the project folder and all the dependencies are added automatically in node_modules directory.

The project setup is ready. We open the app.js and see what is embedded in it . All the dependencies are invoked by the use of require method.

The use of modules in app.js:

  • body-parser — A middleware for handling Raw, Text, JSON and URL encoded form data(especially POST data).
  • Cookie-Parser — To parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • Jade-A template engine . It combines data and the template to produce HTML.
  • Express — A web application framework that provides a set of features for web and mobile applications
  • Morgan — A HTTP request logger middleware for node.js

Now, let’s run our application. Go to the command line
Run the server with

$ npm start

The server gets started and listens to port 3002. Open the browser and load

http://localhost:3002

You will get the output as shown below.

STEP 5

CREATE A MODEL FOLDER
In the model folder we have the config.js,index.js the user.js file which contains the Schema:
config.js


module.exports = {
db: process.env.DB_DATABASE,
dialect:process.env.DB_DIALECT,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
port:process.env.DB_PORT
}

index.js


const {Sequelize} = require(‘sequelize’);
const model = require(‘./models’);
const { user } = require(‘./config’);
const sequelize = new Sequelize(connection.db, connection.user, connection.password, {
host:connection.host,
dialect:connection.dialect,
port: connection.port
});
const db ={};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
const Model = new model(sequelize,Sequelize);
module.exports = db;

User model code


class Model {
constructor(sequelize,Sequelize){
this.sequelize = sequelize,
this.Sequelize = Sequelize
}
User = () =>{
return this.sequelize.define(‘user’,{ id:{type:this.Sequelize.INTEGER,
allowNull:false,
autoIncrement:true,
primaryKey:true},
firstname:{
type:this.Sequelize.STRING,
allowNull:false
},
lastname:{
type:this.Sequelize.STRING,
allowNull:false
},
email :{
type:this.Sequelize.STRING,
allowNull:false,
// validate:{
// isEmail:true
// }
},
password:{
type:this.Sequelize.STRING,
allowNull:false,
unique:true
}
}
);
};

STEP 6

CREATING ROUTES
It send request of specific action to the controller.

User route


var router = express.Router();
const controller = require(‘../controllers/user.controller’);
router.get(‘/:id’, controller.getUser);
router.post(‘/’, controller.createUser);
router.put(‘/:id’, controller.updateUser);
router.delete(‘/:id’, controller.deleteUser);
module.exports = router;

User controller code


const models = require(‘../models/index’);
async function getUser(req,res){
userId = req.params.id;
const user = await models.user.findOne({where:{id:userId},attributes:[‘firstname’,’lastname’]})
res.json(user);
}
async function createUser(req,res){
var data = req.body;
var user, msg;
const checkUser = await models.user.findOne({where:{email:data.email}});
if (checkUser){
msg = “Sorry you already have an account”
} else {
const user = await models.user.create({firstname:data.firstname, lastname:data.lastname,email:data.email, password:data.password});
msg = “Account successfully created”
}
res.json(msg);
}
async function updateUser(req,res){
userId = req.params.id;
var data = req.body;
const user = await models.user.update({firstname:data.firstname, lastname:data.lastname,email:data.email, password:data.password},{where:{id:userId}});
res.json({msg:’User updated successfully’})
}
async function deleteUser(req,res){
userId = req.params.id;
const user = await models.user.destroy({where:{id:req.params.id}});
res.json({mssg:’user deleted’})
}
module.exports = {
getUser,
createUser,
updateUser,
deleteUser
}

--

--