Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request

Build Nodejs CRUD Application with MySQL or PostgreSQL using Express, Sequelize, Ajax for Post-Get-Put-Delete

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

Related posts:


Overview – How to build Nodejs CRUD application?

Architecture Overview

Nodejs Build CRUD Application - Architecture Overview
Nodejs Build CRUD Application – Architecture Overview

We have 4 main blocks for the application:

  • For building RestAPIs in Nodejs application, we use Express framework.
  • For interacting with database MySQL/PostgreSQL, we use Sequelize ORM.
  • We define APIs URL in router.js file
  • We implement how to process each API URL in controller.js file
  • We use Bootstrap and JQuery Ajax to implement frontend client.

Project Structure

Nodejs Build CRUD Application - Project Structure
Nodejs Build CRUD Application – Project Structure
  • config package is used to configure Sequelize and MySQL/PostgreSQL database environment
  • models package is used to define a Sequelize model to interact with database
  • routers package is used to define Rest APIs’ URL
  • controllers is used to implement business logic to processing each RestAPIs
  • views folder is used to implement HTML view pages
  • resources/js folder is used to implement JQuery Ajax to Post/Get/Put/Delete RestAPIs

Goal

– Add new Customer:

Add New Customers
Add New Customers
Database Checking Records
Database Checking Records

– List All Customers:

List All Customers
List All Customers

– Update a Customer

Update a Customer
Update a Customer

– Delete a Customer

Delete a customer Successfully
Delete a customer Successfully

– Check database:

Check database records after deleting
Check database records after deleting

Node.js Backend Development

Create Nodejs project

For building Nodejs CRUD Application, we need to use the below dependencies:

  • body-parser is used to parse a submit form to nodejs server
  • express is used to build restApis
  • mysql2 is used for MySQL driver
  • sequelize is used to do CRUD operation with MySQL/PostgreSQL database

We install them with below commandline:

npm install --save body-parse express mysql2 sequelize

Check the package.json file:

{
  "name": "nodejs-build-crud-application",
  "version": "1.0.0",
  "description": "Nodejs Build Crud Application Post/Get/Put/Delete to MySQL/PostgreSQL with frontend is bootstrap framework",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "Nodejs",
    "RestAPI",
    "Express",
    "Tutorial",
    "MySQL",
    "PostgreSQL",
    "Bootstrap",
    "framework"
  ],
  "author": "https://loizenjava.com",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mysql": "^2.18.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.13"
  }
}

Database Configuration

We define a db.config.js file to configure Sequelize to interact with MySQL/PostgreSQL database:

const env = require('./env.js');
 
const Sequelize = require('sequelize');
const sequelize = new Sequelize(env.database, env.username, env.password, {
  host: env.host,
  dialect: env.dialect,
  operatorsAliases: false,
 
  pool: {
    max: env.max,
    min: env.pool.min,
    acquire: env.pool.acquire,
    idle: env.pool.idle
  }
});
 
const db = {};
 
db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
db.Customer = require('../models/customer.model.js')(sequelize, Sequelize);
 
module.exports = db;

– For MySQL database, we add the below configured environment’s properties in env.js:

const env = {
  database: 'loizenjavadb',
  username: 'root',
  password: '12345',
  host: 'localhost',
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};
 
module.exports = env;

– For PostgreSQL database, we add the below configured environment’s properties in env.js

const env = {
  database: 'loizenjava',
  username: 'postgres',
  password: '123',
  host: 'localhost',
  dialect: 'postgres',
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};
 
module.exports = env;

Define Sequelize Model

I create a Sequelize model customer.model.js for customer entity with 5 properties:

  • id is a primary key having INTEGER type
  • firstname property has STRING type
  • lastname property has STRING type
  • address property has STRING type
  • age property has INTEGER type
module.exports = (sequelize, Sequelize) => {
	const Customer = sequelize.define('customer', {	
	  id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
      },
	  firstname: {
			type: Sequelize.STRING
	  },
	  lastname: {
		type: Sequelize.STRING
  	  },
	  address: {
			type: Sequelize.STRING
	  },
	  age: {
			type: Sequelize.INTEGER
	  }
	});
	
	return Customer;
}

Define Express RestAPIs Router – POST/GET/PUT/DELETE

We define 7 APIs for 2 groups:

– Group 1 provides html page view

  • /is used to getindex.html view
  • /customers/ is used to get customers.html file

– Group 2 provides RestAPIs as below:

  • /api/customer/create is POST RestAPI to POST a new customer
  • /api/customer/retrieveinfos is a GET RestAPI to retrieve all customers’ info
  • /api/customer/findone/:id is a GET RestAPI to get a customer by a given id
  • /api/customer/updatebyid/:id is a PUT RestAPI to update a customer by a given id
  • /api/customer/deletebyid/:id is a DELETE RestAPI to delete a customer by a given id

Coding:

let express = require('express');
let router = express.Router();
 
const customers = require('../controllers/controller.js');

let path = __basedir + '/view/';

router.get('/', (req,res) => {
    console.log("__basedir" + __basedir);
    res.sendFile(path + "index.html");
});

router.get('/customers/', (req,res) => {
    console.log("__basedir" + __basedir);
    res.sendFile(path + "customers.html");
});

router.post('/api/customer/create', customers.create);
router.get('/api/customer/retrieveinfos', customers.retrieveInfos);
router.get('/api/customer/findone/:id', customers.findById);
router.put('/api/customer/updatebyid/:id', customers.updateById);
router.delete('/api/customer/deletebyid/:id', customers.deleteById);

module.exports = router;

Implement RestAPIs Controller

For processing Post/Get/Put/Delete RestAPI requests, we implement controller.js with 5 functions:

  • exports.create = (req, res) is used to create a new Customer (post request processing)
  • exports.retrieveInfos = (req, res) is used to retrieve all Customer’s infos (get request)
  • exports.findById = (req, res) is used to get a customer by given id
  • exports.updateById = async (req, res) is used to update a customer with a given id
  • exports.deleteById = async (req, res) is used to delete a customer with a given id

Post a Customer

exports.create = (req, res) => {
    let customer = {};

    try{
        // Building Customer object from upoading request's body
        customer.firstname = req.body.firstname;
        customer.lastname = req.body.lastname;
        customer.address = req.body.address;
        customer.age = req.body.age;
    
        // Save to MySQL database
        Customer.create(customer).then(result => {    
            // send uploading message to client
            res.status(200).json({
                message: "Upload Successfully!",
                customer: result
            });
        });
    }catch(error){
        res.status(500).json({
            message: "Fail!",
            formdata: customer,
            error: error.message
        });
    }
}

exports.create = (req, res) gets a posting customer’s info via request.body object. Then it uses Sequelize to save the customer object to database. After done, it returns a successfully posting message. Otherwise, a error message will be returned.

Get a Customer

exports.findById = (req, res) => {
    // getting a customer id from request parameters
    let customerId = req.params.id;

    try{
        Customer.findByPk(customerId).then(customer => {
            res.status(200).json({
                message: "Successfully! Retrieve a customer by id = " + customerId,
                customer: customer
            });
        });
    }catch(error) {
        // Send error to Client
        res.statas(500).json({
            message: "Error when retrieving a customer by id = " + customerId,
            error: error.message
        });
    }
}

The function uses Sequelize to find out a Customer object with a given id. After done, It returns a successfully object. Otherwise a error message will be returned.

Get All Customers

exports.retrieveInfos = (req, res) => {
    // find all Customer information from 
    try{
        Customer.findAll({attributes: ['id', 'firstname', 'address']})
        .then(customerInfos => {
            res.status(200).json({
                message: "Get Customers' Infos!",
                customerInfos: customerInfos
            });
        })
    }catch(error) {
        // log on console
        console.log(error);

        res.status(500).json({
            message: "Retrieving Error!",
            error: error
        });
    }
}

The function exports.retrieveInfos = (req, res) retrieves all Customer objects from database with 3 selected attributes: id, firstname, address.

Delete a Customer

exports.deleteById = async (req, res) => {
    try{
        let customerId = req.params.id;
        let customer = await Customer.findByPk(customerId);

        if(!customer){
            res.status(404).json({
                message: "Does Not exist a Customer with id = " + customerId,
                error: "Not Found"
            });
        } else {
            await customer.destroy();
            res.status(200).json({
                message: "Delete Successfully a Customer with id = " + customerId,
                customer: customer
            });
        }
    } catch(error) {
        res.status(500).json({
            message: "Error -> Can NOT delete a customer with id = " + req.params.id,
            error: error.message           
        });
    }
}

The function exports.deleteById = async (req, res) finds a Customer by a given id. If the customer is found, it will be deleted by destroy() function and return back client a successfully message. Otherwise, an error message is returned.

Update a Customer

exports.updateById = async (req, res) => {
    try{
        let customerId = req.params.id;
        let customer = await Customer.findByPk(customerId);
    
        if(!customer){
            // return a response to client
            res.status(404).json({
                message: "Not Found for updating a customer with id = " + customerId
            });
        } else {    
            // update new change to database
            let updatedObject = {
                firstname: req.body.firstname,
                lastname: req.body.lastname,
                address: req.body.address,
                age: req.body.age
            }
            let result = await Customer.update(updatedObject, {returning: true, where: {id: customerId}});
            
            // return the response to client
            if(!result) {
                res.status(500).json({
                    message: "Error -> Can not update a customer with id = " + req.params.id,
                    error: "Can NOT Updated"
                });
            }

            res.status(200).json({
                message: "Update successfully a Customer with id = " + customerId,
                customer: updatedObject           
            });
        }
    } catch(error){
        res.status(500).json({
            message: "Error -> Can not update a customer with id = " + req.params.id,
            error: error.message
        });
    }
}

The function exports.updateById = async (req, res) finds a customer object by a given id. If the customer is found, we change the customer attributes with new values retrieving from request.body object. After done, a successfully message will be returned. Otherwise an error message will be returned.

Create Server.js

const express = require('express');
const app = express();

var bodyParser = require('body-parser');
 
global.__basedir = __dirname;
 
const db = require('./app/config/db.config.js');
  
// force: true will drop the table if it already exists
db.sequelize.sync({force: true}).then(() => {
  console.log('Drop and Resync with { force: true }');
}); 

let router = require('./app/routers/router.js');
app.use(bodyParser.json());
app.use(express.static('resources'));
app.use('/', router);

// Create a Server
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

Backend Testing

Testcase 1 – Create a Customer

– Post a Customer:

Test RestAPI - Post a Customer
Test RestAPI – Post a Customer

– Check database records:

Test with Rest Client - Testcase 1 - Check MySQL Records
Test with Rest Client – Testcase 1 – Check MySQL Records

Testcase 2 – Get a Customer

Test with RestClient - Testcase 2 - get a Customer with a given ID
Test with RestClient – Testcase 2 – get a Customer with a given ID

Testcase 3 – Get all Customers

Test with RestClient - Testcase 3 - Retrieve All Customers
Test with RestClient – Testcase 3 – Retrieve All Customers

Testcase 4 – Delete a Customer

Test with Rest Client - Testcase 4 - Delete a Customer with given id
Test with Rest Client – Testcase 4 – Delete a Customer with given id

Testcase 5 – Update a Customer

Test with Rest Client - Testcase 4 - Delete a Customer with given id
Test with Rest Client – Testcase 4 – Delete a Customer with given id

– Check database records:

Testcase 5 - Check Database records after updating
Testcase 5 – Check Database records after updating

Bootstrap and Ajax Frontend Development

Create HTML Page Views

Create Index.html

We create a index.html page for adding a new customer:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Build CRUD Nodejs Application</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/post_customer.js"></script>
</head>
<body>
	<div class="container">
		<ul class="nav nav-pills">
			<li class="nav-item">
				<a class="nav-link" href="/">Add New</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" href="/customers/">All Customers</a>
			</li>
		</ul>
		<div class="row">
			<div class="col-sm-7" style="background-color:#e6fffa; padding:10px; border-radius:3px">
				<h3>Add new Customer</h3>
				<form id="add_new_customer">
					<div class="form-group">
						<label class="control-label" for="firstname">First Name:</label>
						<input type="text" class="form-control" id="firstname"
								placeholder="Enter First Name" name="firstname" required></input>
                    </div>
					<div class="form-group">
						<label class="control-label" for="lastname">Last Name:</label>
						<input type="text" class="form-control" id="lastname"
								placeholder="Enter Last Name" name="lastname" required></input>
					</div>                    
					<div class="form-group">
						<label class="control-label" for="address">Address:</label>
						<input type="text" class="form-control" id="address"
								placeholder="Enter Address" name="address" required></input>
					</div>                    
					<div class="form-group">
						<label class="control-label" for="age">Age:</label>
						<input type="number" class="form-control" id="age"
								placeholder="Enter Age" name="age" min="18" max="60" required></input>
					</div>                    
					<button type="submit" class="btn btn-danger" id="btn-add-new-customer">Update</button>
				</form>
				<div id="response" style="display:none; margin-top:10px">
				</div>
			</div>
		</div>
		<hr>		
	</div>
</body>
</html>

Showing Customers and Updating Page

Coding:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Build CRUD Nodejs Application</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/update_customer.js"></script>
<script type="text/javascript" src="/js/delete_customer.js"></script>
<script type="text/javascript" src="/js/get_customer.js"></script>
</head>
<body>
	<div class="container">
		<ul class="nav nav-pills">
			<li class="nav-item">
				<a class="nav-link" href="/">Add New</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" href="/customers/">All Customers</a>
			</li>
		</ul>
        <div id="div_customer_table">
			<h1>Customers Table</h1>
			<div class="row col-md-6 table-responsive">
			  <table id="customerTable" class="table table-striped">
				<thead>
				  <tr>
					<th>Id</th>
					<th>Name</th>
					<th>Address</th>
					<th></th>
				  </tr>
				</thead>
				<tbody>
				</tbody>
			  </table>
			</div>
		  </div>
		<div class="row">
			<div class="col-sm-6" style="display: none; 
											background-color:#e6fffa; padding:10px; border-radius:3px" 
									id="div_customer_updating">
				<form id="update_customer_form">
					<div class="form-group">
					<label for="customer_id">Id:</label>
					<input type="text" class="form-control" id="customer_id" readonly>
					</div>
					<div class="form-group">
					<label for="customer_first_name">First Name:</label>
					<input type="text" class="form-control" placeholder="Enter First Name" id="customer_first_name">
					</div>
					<div class="form-group">
						<label for="customer_last_name">Last Name:</label>
						<input type="text" class="form-control" placeholder="Enter Last Name" id="customer_last_name">
					</div>				  
					<div class="form-group">
						<label for="customer_address">Address:</label>
						<input type="text" class="form-control" placeholder="Enter Address" id="customer_address">
					</div>				  				
					<div class="form-group">
						<label for="customer_age">Age:</label>
						<input type="number" class="form-control" 
								placeholder="Enter Age" id="customer_age" min="18" max="60">
					</div>				  				
					<button type="submit" class="btn btn-primary">Submit</button>
				</form>
				<div id="response" style="display:none; margin:10px">
				</div>
			</div>
		</div>
		<hr>

		  <!-- The Modal -->
		  <div class="modal fade" id="delete-modal">
			<div class="modal-dialog modal-dialog-centered">
			  <div class="modal-content">
			  
				<!-- Modal Header -->
				<div class="modal-header">
				  <h4 class="modal-title">Delete!</h4>
				  <button type="button" class="close" data-dismiss="modal">&times;</button>
				</div>
				
				<!-- Modal body -->
				<div class="modal-body">
				</div>
				
				<!-- Modal footer -->
				<div class="modal-footer">
				  <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
				  <button type="button" class="btn btn-danger" id="model-delete-btn">Delete</button>
				</div>				
			  </div>
			</div>
		  </div>
	</div>
</body>
</html>

Implement JQuery Ajax Client

Ajax POST a Customer

post_customer.js:

$(document).ready(function() {
    $("#add_new_customer").submit(function(evt) {
        evt.preventDefault();

        // PREPARE FORM DATA
        let formData = {
            firstname : $("#firstname").val(),
            lastname :  $("#lastname").val(),
            address: $("#address").val(),
            age: $("#age").val()
        }

        $.ajax({
            url: '/api/customer/create',
            type: 'POST',
            contentType : "application/json",
            data: JSON.stringify(formData),
            dataType : 'json',
            async: false,
            cache: false,
            success: function (response) {
                let customer = response.customer;
                let customerString = "{ name: " + customer.firstname + " " + customer.lastname + 
                                            ", address: " + customer.address + 
                                            ", age: " + customer.age  + " }"
                let successAlert = '<div class="alert alert-success alert-dismissible">' + 
                                        '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                                        '<strong>' + response.message + '</strong> Customer\'s Info = ' + customerString;
                                    '</div>'
                $("#response").append(successAlert);
                $("#response").css({"display": "block"});

                resetUploadForm();
            },
            error: function (response) {
                let errorAlert = '<div class="alert alert-danger alert-dismissible">' + 
                                    '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                                    '<strong>' + response.message + '</strong>' + ' ,Error: ' + message.error + 
                                '</div>'
                $("#response").append(errorAlert);
                $("#response").css({"display": "block"});

                resetUploadForm();
            }
        });
    });

    function resetUploadForm(){
        $("#firstname").val("");
        $("#lastname").val("");
        $("#address").val("");
        $("#age").val("");
    }

    (function(){
        let pathname = window.location.pathname;
        if(pathname === "/"){
            $(".nav .nav-item a:first").addClass("active");
        } else if (pathname == "/customers") {
            $(".nav .nav-item a:last").addClass("active");
        }
    })();
});

Ajax GET all Customers

get_customer.js:

$(document).ready(function(){
    (function(){
        $.ajax({
            type : "GET",
            url : "/api/customer/retrieveinfos",
            success: function(response){
              $.each(response.customerInfos, (i, customer) => {  

              /*  <button type="button" class="btn btn-danger btn_delete" data-toggle="modal" data-target="#myModal">
                Open modal
              </button>*/

                let deleteButton = '<button ' +
                                        'id=' +
                                        '\"' + 'btn_delete_' + customer.id + '\"'+
                                        ' type="button" class="btn btn-danger btn_delete" data-toggle="modal" data-target="#delete-modal"' +
                                        '>&times</button>';

                let get_More_Info_Btn = '<button' +
                                            ' id=' + '\"' + 'btn_id_' + customer.id + '\"' +
                                            ' type="button" class="btn btn-info btn_id">' + 
                                            customer.id +
                                            '</button>';
                
                let tr_id = 'tr_' + customer.id;
                let customerRow = '<tr id=\"' + tr_id + "\"" + '>' +
                          '<td>' + get_More_Info_Btn + '</td>' +
                          '<td class=\"td_first_name\">' + customer.firstname.toUpperCase() + '</td>' +
                          '<td class=\"td_address\">' + customer.address + '</td>' +
                          '<td>' + deleteButton + '</td>' +
                          '</tr>';                
                $('#customerTable tbody').append(customerRow);
              });
            },
            error : function(e) {
              alert("ERROR: ", e);
              console.log("ERROR: ", e);
            }
        });
    })();        
    
    (function(){
        let pathname = window.location.pathname;
        if (pathname == "/customers/") {
            $(".nav .nav-item a:last").addClass("active");
        }
    })();
});

Ajax DELETE a Customer

delete_customer.js file:

$(document).ready(function(){
    let customerId = 0;

    $(document).on("click", "#div_customer_table table button.btn_delete", function() {
        let btn_id = (event.srcElement.id);
        customerId = btn_id.split("_")[2];

        $("div.modal-body")
            .text("Do you want delete a Customer with id = " + customerId + " ?");
    });

    $(document).on("click", "#model-delete-btn", function() {
        $.ajax({
            url: '/api/customer/deletebyid/' + customerId,
            type: 'DELETE',
            success: function(response) {
                $("div.modal-body")
                    .text("Delete successfully a Customer with id = " + customerId + "!");

                $("#model-delete-btn").remove();
                $("button.btn.btn-secondary").text("Close");

                // delete the customer row on html page
                let row_id = "tr_" + customerId;
                $("#" + row_id).remove();
                $("#div_customer_updating").css({"display": "none"});
            },
            error: function(error){
                console.log(error);
                $("#div_customer_updating").css({"display": "none"});
                alert("Error -> " + error);
            }
        });
    });
});

Ajax UPDATE a Customer

update_customer.js:

$(document).ready(function(){
    $("#update_customer_form").submit(function(evt) {
        evt.preventDefault();
        try {
            let customerId = $("#customer_id").val();

            // PREPARE FORM DATA
            let formData = {
                firstname : $("#customer_first_name").val(),
                lastname :  $("#customer_last_name").val(),
                address: $("#customer_address").val(),
                age: $("#customer_age").val()
            }
            
            $.ajax({
                url: '/api/customer/updatebyid/' + customerId + "/",
                type: 'PUT',
                contentType : "application/json",
                data: JSON.stringify(formData),
                dataType : 'json',
                async: false,
                cache: false,
                success: function (response) {
                    let customer = response.customer;
                    let customerString = "{firstname:" + customer.firstname + 
                                                " ,lastname:" + customer.lastname + 
                                                ", address:" + customer.address + 
                                                ", age:" + customer.age  + "}"
                    let successAlert = '<div class="alert alert-success alert-dismissible">' + 
                                            '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                                            '<strong>' + response.message + '</strong> Customer\'s Info = ' + customerString;
                                        '</div>'

                    // change the updated data for customer table record
                    $("#tr_" + customerId + " td.td_first_name").text(customer.firstname.toUpperCase());
                    $("#tr_" + customerId + " td.td_address").text(customer.address.toUpperCase());

                    $("#response").empty();
                    $("#response").append(successAlert);
                    $("#response").css({"display": "block"});
                },

                error: function (response) {
                    let errorAlert = '<div class="alert alert-danger alert-dismissible">' + 
                                        '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
                                        '<strong>' + response.message + '</strong>' + ' ,Error: ' + message.error + 
                                    '</div>';

                    $("#response").empty();                                    
                    $("#response").append(errorAlert);
                    $("#response").css({"display": "block"});
                }
            });
        } catch(error){
            console.log(error);
            alert(error);
        }
    });

    $(document).on("click", "table button.btn_id", function(){
        let id_of_button = (event.srcElement.id);
        let customerId = id_of_button.split("_")[2];
  
        $.ajax({
            url: '/api/customer/findone/' + customerId,
            type: 'GET',
            success: function(response) {
                let customer = response.customer;                
                $("#customer_id").val(customer.id);
                $("#customer_first_name").val(customer.firstname);
                $("#customer_last_name").val(customer.lastname);
                $("#customer_address").val(customer.address);
                $("#customer_age").val(customer.age);
                $("#div_customer_updating").css({"display": "block"});
            },
            error: function(error){
                console.log(error);
                alert("Error -> " + error);
            }
        });        
    });
});

Frontend Testing

Testcase 1 – Add new Customer

Testcase with Frontend - Testcase 1 - Add new Customer
Testcase with Frontend – Testcase 1 – Add new Customer
Testcase with Frontend - Testcase 1 - Add new Customer - Successfully
Testcase with Frontend – Testcase 1 – Add new Customer – Successfully

Testcase 2 – Show All Customer

Testcase with Frontend - Testcase 2 - Retrieve All Customers
Testcase with Frontend – Testcase 2 – Retrieve All Customers
Test with Frontend - Testcase 2 - Load all Customers
Test with Frontend – Testcase 2 – Load all Customers

Testcase 3 – Get a Customer

Test with Frontend - Testcase 3 - Load a Customer
Test with Frontend – Testcase 3 – Load a Customer
Test with Frontend - Test case 3 - Load a Customer - Successfully
Test with Frontend – Test case 3 – Load a Customer – Successfully

Testcase 4 – Update a Customer

Testcase 4 - Update a Customer successfully
Testcase 4 – Update a Customer successfully

Testcase 5 – Delete a Customer

Test with Frontend - Testcase 5 - Delete a Customer - part 1
Test with Frontend – Testcase 5 – Delete a Customer – part 1
Test with Frontend - Test case 5 - Delete Successfully
Test with Frontend – Test case 5 – Delete Successfully

Sourcecode

I include a running sourcecode for the tutorial with the implemented features:

Nodejs Build CRUD Application

– Github sourcecode:

Nodejs Build CRUD Application – GitHub Sourcecode

2 thoughts on “Build Nodejs CRUD Application with MySQL/PostgreSQL – Express RestAPIs + Ajax : Post/Get/Put/Delete Request”

Leave a Reply

Your email address will not be published. Required fields are marked *