NodeJS/Express Rest APIs + Bootstrap Table + Ajax JQuery example

In the tutorial, we show how to use Bootstrap Table & Ajax JQuery to show data from NodeJS/Express RestAPIs.

Related posts:
Integrate NodeJS/Express – JQuery Ajax POST/GET – Bootstrap view
NodeJs/Express RestAPIs – POST/GET/PUT/DELETE requests

Goal

We create a NodeJS/Express project as below structure:


/NodeJS-Express-Ajax-JQuery-Bootstrap-Table
	/app
		/controllers
			customer.controller.js
		/routes
			customer.route.js
	/node_modules
	/resources
		/static
			/jquery
				ajaxLoadData.js
	/views
		404.html
		index.html
	package.json
	package-lock.json
	server.js

Run above project then makes a request http://localhost:8081:

-> Bootstrap view:

NodeJS-Express-Ajax-JQuery-Bootstrap-Table-view

Practice

Setting up NodeJS/Express project

Create a folder ‘NodeJS-Express-Ajax-JQuery-Bootstrap-Table’:


mkdir NodeJS-Express-Ajax-JQuery-Bootstrap-Table
cd NodeJS-Express-Ajax-JQuery-Bootstrap-Table

Then init NodeJS project, see prompts:


NodeJS-Express-Ajax-JQuery-Bootstrap-Table>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs-express-ajax-jquery-bootstrap-table)
version: (1.0.0)
description: Build NodeJS-Express web-app that loads data on view using Bootstrap Table + Ajax JQuery
entry point: (index.js) server.js
test command:
git repository:
keywords: NodeJS, Express, Bootstrap-Table, Ajax-Jquery
author: grokonez.com
license: (ISC)
About to write to C:\Users\pc\Desktop\nodejs\NodeJS-Express-Ajax-JQuery-Bootstrap-Table\package.json:

{
  "name": "nodejs-express-ajax-jquery-bootstrap-table",
  "version": "1.0.0",
  "description": "Build NodeJS-Express web-app that loads data on view using Bootstrap Table + Ajax JQuery",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Bootstrap-Table",
    "Ajax-Jquery"
  ],
  "author": "grokonez.com",
  "license": "ISC"
}


Is this ok? (yes) yes

-> Install Express, Body-Parser:


npm install express body-parser --save

-> see package.json file:


{
  "name": "nodejs-express-ajax-jquery-bootstrap-table",
  "version": "1.0.0",
  "description": "Build NodeJS-Express web-app that loads data on view using Bootstrap Table + Ajax JQuery",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "NodeJS",
    "Express",
    "Bootstrap-Table",
    "Ajax-Jquery"
  ],
  "author": "grokonez.com",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3"
  }
}

Frontend

Create Bootstrap views

./view/index.html file:

<!DOCTYPE HTML>
 
<html>
<head>
      <title>NodeJS/Express APIs- Bootstrap Table + JQuery</title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	  <script src="/static/jquery/ajaxLoadData.js"></script>
</head>
 
<body>
<div class="container">
	<h1>Customers Table</h1>
		<div class="row col-md-7 table-responsive">
			<table id="customerTable" class="table table-bordered table-hover">
				<thead>
					<tr>
						<th>Id</th>
						<th>Name</th>
						<th>Age</th>
						<th>Street</th>
						<th>Postcode</th>
					</tr>
				</thead>
				<tbody>
				</tbody>
			</table>
		</div>
	</div>
	
</body>
</html>

./views/404.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>404 Error!</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  
<div class="jumbotron text-center">
  <h1>404 Error!</h1>
  <p>PAGE NOT FOUND</p>
</div>
</body>
</html>

AJax JQuery load data into Bootstrap Table

– For Ajax JQuery Load data into Bootstrap Table, we implement a file ./resources/static/jquery/ajaxLoadData.js:


$(document).ready(function() {
	
	ajaxGet();
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : window.location + "api/customer/all",
			success: function(result){
				$.each(result, function(i, customer){
					
					var customerRow = '' +
										'' + customer.id + '' +
										'' + customer.name.toUpperCase() + '' +
										'' + customer.age + '' +
										'' + customer.address.street + '' +
										'' + customer.address.postcode + '' +
									  '';
					
					$('#customerTable tbody').append(customerRow);
					
		        });
				
				$( "#customerTable tbody tr:odd" ).addClass("info");
				$( "#customerTable tbody tr:even" ).addClass("success");
			},
			error : function(e) {
				alert("ERROR: ", e);
				console.log("ERROR: ", e);
			}
		});	
	}
})

Backend

Create Express Routes

./app/routes/customer.route.js file:


module.exports = function(app) {
 
	var express = require("express");
	var router = express.Router();
	
    const customers = require('../controllers/customer.controller.js');
	
	var path = __basedir + '/views/';
	
	router.use(function (req,res,next) {
		console.log("/" + req.method);
		next();
	});
	
	app.get('/', (req,res) => {
		res.sendFile(path + "index.html");
	});
 
    // Retrieve all Customers
    app.get('/api/customers/all', customers.getAll);
	
	app.use("/",router);
 
	app.use("*", (req,res) => {
		res.sendFile(path + "404.html");
	});
}

Implement Controllers

./app/controllers/customer.controller.js file:


// Fetch all Customers
var customers = [
					{
						id: 1,
						name: "Jack",
						age: 25,
						address:{
							street: "NANTERRE CT", "77471",
							postcode: "77471"
						}
					},
					{
						id: 2,
						name: "Mary",
						age: 37,
						address:{
							street: "W NORMA ST",
							postcode: "77009"
						}
					},
					{
						id: 3
						name: "Peter",
						age: 17,
						address:{
							street: "S NUGENT AVE",
							postcode: "77571"
						}
					},
					{
						id: 4,
						name: "Peter",
						age: 17,
						address:{
							street: "E NAVAHO TRL",
							postcode: "77449"
						}
					},
					{
						id: 5,
						name: "Craig",
						age: 45,
						address: {
							street: "AVE N",
							postcode: "77587"
						}
					}
			]
			
exports.getAll = (req, res) => {
	console.log("--->Get All Customers: \n" + JSON.stringify(customers, null, 4));
    res.send(customers)); 
};

Implement Server.js

./server.js file:


var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())

app.use(express.static('resources'));
global.__basedir = __dirname;
 
require('./app/routes/customer.route.js')(app);

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

Run & Check results

Start NodeJS server, then makes a request: http://localhost:8081
-> Logs:


NodeJS-Express-Ajax-JQuery-Bootstrap-Table>node server.js
App listening at http://:::8081
--->Get All Customers:
[
    {
        "id": 1,
        "name": "Jack",
        "age": 25,
        "address": {
            "street": "NANTERRE CT",
            "postcode": "77471"
        }
    },
    {
        "id": 2,
        "name": "Mary",
        "age": 37,
        "address": {
            "street": "W NORMA ST",
            "postcode": "77009"
        }
    },
    {
        "id": 3,
        "name": "Peter",
        "age": 17,
        "address": {
            "street": "S NUGENT AVE",
            "postcode": "77571"
        }
    },
    {
        "id": 4,
        "name": "Amos",
        "age": 23,
        "address": {
            "street": "E NAVAHO TRL",
            "postcode": "77449"
        }
    },
    {
        "id": 5,
        "name": "Craig",
        "age": 45,
        "address": {
            "street": "AVE N",
            "postcode": "77587"
        }
    }
]

-> Browser Network’s Logs:

NodeJS-Express-Ajax-JQuery-Bootstrap-Table-request-logs

-> Bootstrap views:

NodeJS-Express-Ajax-JQuery-Bootstrap-Table-view

Sourcecode

To run below sourcecode, follow the guides:


step 0: download & extract zip file -> we have a folder ‘NodeJS-Express-Ajax-JQuery-Bootstrap-Table’
step 1: cd NodeJS-Express-Ajax-JQuery-Bootstrap-Table
step 2: npm install express body-parser –save
step 3: node server.js

-> Sourcecode:
NodeJS-Express-Ajax-JQuery-Bootstrap-Table



By grokonez | May 8, 2018.

Last updated on April 30, 2021.



Related Posts


1 thought on “NodeJS/Express Rest APIs + Bootstrap Table + Ajax JQuery example”

Got Something To Say:

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

*