Devstringx Technologies's profile

How to develop API with NodeJS and Express

How to develop API with NodeJS and Express
Basic Installation & requirements
Node.js is an open-source, cross-platform, JavaScript runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript.

Initiate Node Js app with: npm init -y
Express is the most popular Node.js web application framework that provides a robust set of features to help in developing web and mobile applications.
Install express with node Js: npm install express
To access a MySQL database with Node.js, you need to install a MySQL driver. This tutorial will help in using the “MySQL” module, downloaded from NPM. To download and install the “MySQL” module, you need to open the Command Terminal and execute the following:
Download Xampp to run MySql
https://www.apachefriends.org/download.html

You need to open the control panel of Xampp and start MySQL & Http service
Then
npm install MySQL
Nodemon is a tool that helps in developing node.js based applications by automatically restarting the node application when file changes in the directory are detected.
https://www.npmjs.com/package/nodemon
  npm install nodemon
Postman Quickly and easily send REST, SOAP, and GraphQL requests directly
header: Content-Type : x-www.form-urlencoded
Database structure:
 CREATE TABLE `users` (
`id` int(11) NOT NULL,
`fname` varchar(100) DEFAULT NULL,
`lname` varchar(100) DEFAULT NULL,
`email` varchar(256) DEFAULT NULL,
`pasword` varchar(128) DEFAULT NULL,
`gender` enum(‘m’,’f’) DEFAULT NULL,
`number` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Folder Structure : package.json
{
  “name”: “node project”,
“version”: “1.0.0”,
“description”: “”,
“main”: “app.js”,
“scripts”: {
    “test”: “echo \”Error: no test specified\” && exit 1″,
“start”: “nodemon app.js”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“dependencies”: {
    “bcrypt”: “^3.0.8”,
    “dotenv”: “^8.2.0”,
    “express”: “^4.17.1”,
    “mysql”: “^2.18.1”
  },
  “devDependencies”: { }
}
app.js
require(‘dotenv’).config();
//required express

const express = require(“express”);
const app = express();

//required body parser
const bodyParser = require(‘body-parser’);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//call routers
const userinsertRouter = require(“./api/users/user.router”);
//Define api url’s
app.use(express.json());
app.use(“/api/users”,userinsertRouter); 
app.listen(process.env.APP_PORT, ()=> {
  console.log(process.env.APP_PORT)
});
database.js
let mysql = require(‘mysql’);
let pool = mysql.createConnection({
    host: ‘localhost’,
    user: ‘root’,
    password: ”,
    database: ‘nodetest’
});
pool.connect(function(err) {
    if (err) {
      return console.error(‘error: ‘ + err.message);
    }
console.log(‘Connected to the MySQL server.’);
});
module.exports = pool;
user.router.js
const { createUser, updateUser, allUsers, GetUserById, DeleteUserById } = require(“./user.controller”);
const router = require(“express”).Router();
//insert user
router.post(“/create”, createUser);
//update user
router.post(“/update”, updateUser);
//select all users
router.get(“/AllUsers”, allUsers);
//Get user by id
router.get(“/”, GetUserById);
//Delete user
router.delete(“/”, DeleteUserById);
module.exports = router; 
user.controller.js

const { create,update, all,deleteuserbyid_ser,getUserById_ser } = require(“./user.service”); 
module.exports = {
    createUser: (req, res) => {
        const body = req.body;
        // console.log(body);
        create(body, (err, results) =>{
            if(err){
                return res.status(500).json({
                    success: 0,
                    message: “Database connection error”
                });
            }
            return res.status(200).json({
                success: 1,
                message: results
            });
        });
    },
updateUser: (req, res) => {
      const body = req.body;
        update(body, (err, results) =>{
  if(err){          
                return res.status(500).json({
                    success: 0,
                    message: “Database connection error”
                });
            }
            return res.status(200).json({
                success: 1,
                message: results
            });
        });
    },
allUsers: (req, res) =>{
    all(null, (err, result) =>{
        if(err){
            return res.status(500).json({
                Success:0,
                message:”Database connection error”
            });
        }
        return res.status(200).json({
            success: 1,
            message: result
        });
    });
},
GetUserById: (req,res) =>{
        const body = req.body;
        getUserById_ser(body,(err,result)=>{
if(err){
                return res.status(500).json({
                    success:0,
                    message: “database connection error”
                });
            }
            return res.status(200).json({
                success:1,
                message:result
            });
        });
    },
DeleteUserById: (req,res) =>{
        const body = req.body;
        deleteuserbyid_ser(body,(err,result)=>{
            if(err){
                return res.status(500).json({
                    success:0,
                    message: “database connection error”
                });
            }
            return res.status(200).json({
                Success:1,
                message:”User deleted successfully”
            });
        });
    }
};
user.service.js
const pool = require(“../../config/database”);
module.exports = {
    create: (data, callBack) => {
        pool.query (
            ‘insert into users(fname, lname, gender, email, pasword, number) values(?,?,?,?,?,?)’,[data.firstName,data.lastName,data.gender,data.email,       data.password,data.number],
(error, results, fields) => {
    if(error){
        return callBack(error);
    }
                return callBack(null,results);
            }
        )
    },
update: (data, callBack) => {
        pool.query (
            “UPDATE users SET fname=?, lname=?, gender=?, email=?, pasword=?, number=? Where id = ?”,[data.firstName,data.lastName,data.gender,data.email,                data.password,data.number,data.id],
(error, results, fields) => {
                if(error){
                    return callBack(error);
                }
                return callBack(null,results);
            }
        )
    },
all: (data, callBack) => {
        pool.query(‘SELECT * FROM   users’,(error, results, fields) => {
            if(error){
                return callBack(error);
            }
            return callBack(null,results);
        })
    },
getUserById_ser:(data,callBack) => {
  pool.query(‘SELECT * FROM users where id = ?’ , [data.id],  (error,results,fields) => {
            if(error){
                return callBack(error);
            }
            return callBack(null,results);
        })
    },
deleteuserbyid_ser:(data,callBack)=>{
        pool.query(‘Delete From users where id = ?’,[data.id],(err,results,fields)=>{
            if(err){
                return callBack(err);
            }
            return callBack(null,results);
        })
    }
}


How to develop API with NodeJS and Express
Published:

How to develop API with NodeJS and Express

Published:

Creative Fields