May 18, 2022 11:59:00 AM | Product Updates Shoplazza | Build a CRUD Application with Express & NoSql

Explore a very simple project which is to develop a Node JS application that serves several different purposes.

Let's talk about a very simple project which is to develop a Node JS application that serves following purposes:

  • Create a static website with Express.
  • Manage an SQL database (PostgresSQL in this case).
  • Next time, we will talk about how to deploy your static website or node.js framework to AWS S3 buckets.

Obviously, NodeJs is a trendy tech that help millions of javascript based programmers or coders to not just work out the front end but the back end as well. It is so awesome, simply using NPM to import tons of useful libraries and dependencies to make your application stay ahead of others.

You must be wondering and dazzled by all these fancy database terminologies, sql,mysql, nosql, postgresql etc. Basically, let's divide database into two genres:

  1. Relational database, where a type of database that stores and provides access to data points that are related to one another. … The columns of the table hold attributes of the data, and each record usually has a value for each attribute, making it easy to establish the relationships among data points. When you heard MySQL, Oracle DB, or cloud relational DB, such as AWS cloud RDS, IBM DB2 on cloud, SQL Azure etc, there are perfect examples of relational databases.
  2. Non-relational database, is a database that does not use the tabular schema of rows and columns found in most traditional database systems. … The term NoSQL refers to data stores that do not use SQL for queries, and instead use other programming languages and constructs to query the data. In simple terms, NoSQL involves actions of pairing keys and values to any data objects. When people refer to MongoDB, Apache Cassandra, Reddis, they are the examples of NoSQL.

It is worth noting that AWS DynamoDB is an exception and powerful database which can integrate both relational and non-relational database, which we will talk about another time and how to deploy applications on AWS beanstalk while integrating other database or virtual engine services.

Table of Contents

  1. Create NodeJs project
  2. Add modules to the Node project
  3. Create the Express application
  4. Add EJS
  5. Add Views in Express
  6. Start with node-postgres module
  7. Work on an existing row
  8. Create a new row
  9. Delete an existing row
  10. Conclusion

Start with the command line (or “Command prompt” in Windows):

E:\> cd Code
E:\Code> mkdir AppTestPG

This creates a sub-folder “AppTestPG” in my “E:\Code” directory that is used to test different things.

Tips:

Using "./" before any repository may help your code editors, like VScode to better recognize the path to your exact local directory.

Launch Visual Code to open the “AppTestPG” folder:

E:\Code> cd AppTestPG
E:\Code\AppTestPG> code .

To do this, open the Visual Code terminal and run the npm init command:

Menu : View / Terminal
Or shortcut: Ctrl + Backtick;

=>

PS E:\Code\AppTestPG> npm init -y

=>

Wrote to E:\Code\AppTestPG\package.json:{
"name": "AppTestPG",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

Note: For this example, it is faster to do npm init -y (or npm init -yes) than to type at each question to accept the default value.

In Visual Code, the “package.json” file created by NPM now appears in the root folder of the project (“E:\Code\AppTestPG” in this case).

The objective of this demonstration is to test the development of a web-based Node application. To do this, you must install Express because it is the most commonly used Node framework for this type of application.

Express needs a template system to generate views. To avoid complicating things, I choose EJS: there is real HTML in it and it looks a lot like the ASP syntax (before Razor).

To manage the database, this time I’m starting with a rather classic choice, namely PostgreSQL. With Node JS, it is the module “node-postgres” that serves as the interface for PostgreSQL.

This is done in the command line, in the Visual Code terminal:

PS E:\Code\AppTestPG> npm install express
PS E:\Code\AppTestPG> npm install ejs
PS E:\Code\AppTestPG> npm install pg

Note: you have to use the name/identifier “pg” to install the “node-postgres” module.

Or to go faster:

PS E:\Code\AppTestPG> npm install express ejs pg

When the installation of these three dependencies (and their own dependencies) is complete, the “package.json” file contains a new “dependencies” section that saves the list of project dependencies:

{
"name": "AppTestPG",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^2.7.1",
"express": "^4.17.1",
"pg": "^7.12.1"
}
}

Note: In older tutorials, we still see the syntax npm install --save xxxxx to save the list of dependencies in the "package.json" file, but this is no longer necessary since NPM version 5.

The “node_modules” subdirectory is used by NPM to store all the dependency files of a Node project.

When the project is versioned in GIT, this folder must be ignored so that it is not committed in the repository:

  • It’s usually a huge file.
  • The npm install command without argument allows to (re)install dependencies

To test this, you can delete the “node_modules” folder:

PS E:\Code\AppTestPG> rd node_modules /s /q

Note: Under Windows, the /s /q options allow you to delete everything without question.

Then we install all the dependencies listed in the “package.json” file:

PS E:\Code\AppTestPG> npm install

To be sure that everything is installed correctly, the safest way is to start with a “index.js” file with a minimum content:

const express = require("express");const app = express();app.listen(3000, () => { {
console.log("Server started (https://www.shoplazza.com/) !");
});
app.get("/", (req, res) => { {
res.send ("Hello world...");
});

Then, in the Visual Code terminal:

PS E:\Code\AppTestPG> node index

=>

Server started (https://www.shoplazza.com/) !

All we have to do now is check that it really works:

The message “Hello world…” should appear as below:

It’s OK => stop the server by typing Ctrl+C in the Visual Code terminal.

The first line references / imports the Express module.

const express = require("express");

The following line is used to instantiate an Express server.

const app = express();

This server is then started and waits for requests on port 3000. The callback function is used to display an informative message when the server is ready to receive requests.

app.listen(3000, () => { {
console.log("Server started (https://www.shoplazza.com/) !");
});

Then comes a function to answer GET requests pointing to the root of the site.

app.get("/", (req, res) => { {
res.send ("Hello world...");
});

Roughly speaking…

It doesn’t seem so, but the app.get() method does a lot of things in only 3 lines of code.

It responds to HTTP GET requests that arrive on the URL that is passed to it with the 1st parameter. In our case, it is “/”, i.e. the root of the site.

When such a request hit the server, it is passed to the callback function which is defined as a 2nd parameter. Here, it is the following arrow function:

(req, res) => {
res.send ("Hello world...");
}

This callback function receives two objects in parameters that are quite common for any good web server these days:

  • the variable req which contains a Request object
  • the variable res that contains a Response object

The Request object is the HTTP request that was sent by the browser (or any other client). You can therefore find information about this request, such as parameters, headers, cookies, body, etc....

The Response object is the HTTP response that will ultimately be returned to the browser (or any other client).

In our program, the answer will be the text “Hello world…” that is sent using the Response.send() method, which does "just" two things:

  • It returns the text in the body part of the HTTP response
  • It terminates the connection

Note: It’s quite technical for this tutorial.

Let’s get back to simpler things. In the “scripts” section of the “package.json” file, it is recommended to add a line to “automate” the launch of the Node application:

"start": "node index"

This gives (without forgetting the comma at the end of the line):

{
"name": "AppTestPG",
"version": "1.0.0.0",
"description":"",
"hand": "index.js",
"scripts": {
"start": "node index",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^2.7.1",
"express": "^4.17.1",
"pg": "^7.12.1"
}
}

The program can now be started by running:

PS E:\Code\AppTestPG> npm start

=>

> AppTestPG@1.0.0 start E:\Code\AppTestPG
> node index.js
Server started (https://www.shoplazza.com/) !

And don’t forget the Ctrl+C to stop the Express server at the end.

Note: It is possible to use the “nodemon” module to avoid having to stop / restart the server each time the source code is modified. But I prefer not to talk about too many things at once in this tutorial.

In the case of the view corresponding to the request to the site root (i.e. a “GET /”), it will therefore be necessary to create the “index.ejs” view and the two reusable partial views “_header.ejs” and “_footer.ejs”.

Note: These three files must be saved in a “views” folder, which must therefore be created first.

<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>AppTestPG</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">AppTestPG</a>
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/data">Data</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/books">Books</a>
</li>
</ul>
</nav>
<%- include("_header") -%><h1>Hello world...</h1><%- include("_footer") -%>
<footer>
<p>&copy; 2019 - AppTestPG</p>
</footer>
</div></body></html>

Note: Apart from the two <%- include(partial_view) -%>, it is only HTML. This is one of the advantages of EJS over other template engines to avoid having to get distracted when you start.

As you can see in the three views above, they refer to Bootstrap 4.

Written By: shoplazza.com

Learn the essentials for starting, running, and growing an online business and updates about Shoplazza.