0% found this document useful (0 votes)
12 views177 pages

Unit II - Server Side Programming With Node JS

The document outlines a training program aimed at addressing the digital skills gap for over 10 million young professionals, focusing on full stack web development with a specific emphasis on server-side programming using Node.js. It covers the fundamentals of web servers, the Node.js runtime environment, its execution model, features, advantages, and applications. Additionally, it provides guidance on setting up the Node.js development environment and using its REPL for testing JavaScript code.

Uploaded by

SUGUMARAN - BCA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views177 pages

Unit II - Server Side Programming With Node JS

The document outlines a training program aimed at addressing the digital skills gap for over 10 million young professionals, focusing on full stack web development with a specific emphasis on server-side programming using Node.js. It covers the fundamentals of web servers, the Node.js runtime environment, its execution model, features, advantages, and applications. Additionally, it provides guidance on setting up the Node.js development environment and using its REPL for testing JavaScript code.

Uploaded by

SUGUMARAN - BCA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

We are on a mission to address the digital

skills gap for 10 Million+ young professionals,


train and empower them to forge a career
path into future tech
MCA4201- FULL STACK WEB DEVELOPMENT
UNIT-II SERVER SIDE PROGRAMMING WITH NODE JS
Introduction to Web Design

Agenda

• Introduction to Web Servers

• Javascript in the Desktop with NodeJS

• NPM - Serving files with the http module

• Introduction to the Express framework

• Server-side rendering with Templating

• Engines Static Files - async/await

• Fetching JSON from Express

3 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web
servers
Please download pictures in
suitable size here and insert them
by clicking the symbol above.

4 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web servers

Introduction

• A web server is a software or hardware system that processes requests and delivers web pages to
users over the Internet or a private network. It serves HTML pages, images, videos, and other
web content to browsers via HTTP (Hypertext Transfer Protocol) or HTTPS (secure version of
HTTP).

• The term web server can mean one of two things:

• A computer program that accepts HTTP requests and returns HTTP responses with optional data
content.

• A computer that runs a computer program as described above.

• A Web server typically serves static content residing on a file system (HTML Pages, images,
audio and video files).

• Web servers route requests for dynamic content (Non-Web Content) using “Web Gateways”.
5 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2
Introduction to web servers

Web Server Working

• When client sends request for a web page, the web server search for the requested page if

requested page is found then it will send it to client with an HTTP response.

6 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web servers

Web Server Working

• If the requested web page is not found, web server will the send an HTTP response: Error 404 Not

found.

• If client has requested for some other resources then the web server will contact to the application

server and data store to construct the HTTP response.

7 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web servers

Examples of webservers

Apache HTTP Server:

• This is the most popular web server in the world developed by the Apache Software Foundation.

• Apache web server is an open source software and can be installed on almost all operating systems

including Linux, UNIX, Windows, FreeBSD, Mac OS X and more. About 60% of the web server

machines run the Apache Web Server.

8 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web servers

Examples of webservers

Internet Information Services (IIS):

• The Internet Information Server (IIS) is a high performance Web Server from Microsoft. This web

server runs on Windows NT/2000 and 2003 platforms (and may be on upcoming new Windows

version also).

• IIS comes bundled with Windows NT/2000 and 2003; Because IIS is tightly integrated with the

operating system so it is relatively easy to administer it.

9 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web servers

Examples of webservers

Sun Java System Web Server:

• This web server from Sun Microsystems is suited for medium and large web sites.

• Though the server is free it is not open source.

• It however, runs on Windows, Linux and UNIX platforms. The Sun Java System web server supports

various languages, scripts and technologies required for Web 2.0 such as JSP, Java Servlets, PHP,

Perl, Python, and Ruby on Rails, ASP and Coldfusion etc.

10 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Introduction to web servers

Architecture

• For detailed discussion on web server and its architecture,

• kindly refer the content--- “Computer Network basics-> Web System Architecture”

11 MCA4201- FULL STACK WEB DEVELOPMENT | © SmartCliff | Internal | Version 1.2


Javascript in the Desktop
with NodeJS
Please download pictures in
suitable size here and insert them
by clicking the symbol above.

12 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Getting started with Node.js

• Node.js is an open-source server-side runtime environment

• Built on Chrome's V8 JavaScript engine.

• Developed by Ryan Dahl in 2009. Its latest version is v0.10.36.

• It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment

– for building highly scalable server-side applications using JavaScript.

• It provides a rich library of various JavaScript modules which simplifies the development of
web applications using Node.js to a great extent.

Node.js = Runtime Environment + JavaScript Library

13 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Getting started with Node.js

• Why Node.js is called as server-side runtime environment?

Node JS

Build-in Modules
JavaScript
JavaScript on the Server
V8 Engine API

V8 Engine

Running on Node.js

14 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Getting started with Node.js

• Chrome's V8 JavaScript engine was used by JavaScript to execute the code in browser.

• Node JS also used Chrome's V8 JavaScript engine to execute the code on server-side.

• In client side we can run HTML, CSS and JavaScript with the help of using browser.

• We can also run the JavaScript code in server side with the help of Node JS. Here we no need of

browser to run the JavaScript code, We can run our JavaScript code in Node JS with the help of PC

itself.

• That’s why Node JS called as a server-side runtime environment.

15 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Getting started with Node.js

• Is Node JS is a programming language?

• Node. JS is not a programming language. Rather, it's a runtime environment that's used to run JavaScript

outside the browser.

• Is Node JS is a Framework?

• Node JS is not a framework, but It is used to build scalable network applications using an event-driven,

non-blocking I/O model, which makes it fast and light on resources. It allows developers to use a single

language (JavaScript) on both the server-side and the Client-Side.

16 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Getting started with Node.js

• What is Runtime environment?

• A runtime environment (RTE) is a collection of web APIs that a developer can use to create a code and a

JavaScript engine to parse that code.

• We write the built-in modules code through JavaScript code and run it on Node JS v8 engine. During

runtime the Node JS will call the modules through API and produce the output.

17 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Execution Model


Traditional Web Server Model
• In the traditional web server model,

– each request is handled by a dedicated thread from the thread pool.

– If no thread is available in the thread pool at any point of time then the request waits till the next
available thread.

– Dedicated thread executes a particular request and does not return to thread pool until it completes the
execution and returns a response.

18 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Execution Model

• Node.js processes user requests differently when compared to a traditional web server model.

• Node.js runs in a single process and the application code runs in a single thread

– So it needs less resources than other platforms.

• All the user requests to web application will be handled by a single thread and all the I/O work or long
running job is performed asynchronously for a particular request.

– So, this single thread doesn't have to wait for the request to complete and is free to handle the next
request.

– When asynchronous I/O work completes then it processes the request further and sends the response.

• An event loop is constantly watching for the events to be raised for an asynchronous job and executing
callback function when the job completes.

19 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Execution Model

Asynchronous web server model using Node.js

20 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Features of Node.js

• Asynchronous and Event Driven

– All APIs of Node.js library are asynchronous, that is, non-blocking.

– It essentially means a Node.js based server never waits for an API to return data. The server moves to

the next API after calling it.

– A notification mechanism of Events of Node.js helps the server to get a response from the previous API

call.

• Very Fast

− Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.

21 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Features of Node.js

• Single Threaded but Highly Scalable

– Node.js uses a single threaded model with event looping.

– Event mechanism helps the server to respond in a non-blocking way and makes the server highly

scalable as opposed to traditional servers which create limited threads to handle requests.

– Node.js uses a single threaded program and the same program can provide service to a much larger

number of requests than traditional servers like Apache HTTP Server.

• No Buffering

− Node.js applications never buffer any data. These applications simply output the data in chunks.

22 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Advantages of Node.js
• Node.js offers an Easy Scalability

• Easy to Learn

• Single Programming Language

• The Benefit of Fullstack JS

• High Performance

• Large and Active Community

• Advantage of Caching

• Freedom to Develop Apps

• Support for Commonly Used Tools

• Handles the Requests Simultaneously

• Highly Extensible
23 Node.js | © Smartcliff | Internal | Version 1.0
Javascript in the Desktop with NodeJS

Applications of Node.js
• Node.js can be used efficiently in many kinds of applications.

• Some of the most popular solutions includes,

– IoT applications

– real-time chats,

– real-time collaboration tools,

– streaming apps

– Apps with microservices architecture

• A large number of corporate giants have adopted Node.js application development like PayPal,
LinkedIn, Netflix, Uber, GoDaddy, eBay, and so on.

24 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Environment Setup
• Node.js development environment can be setup in Windows, Mac, Linux and Solaris.

• The following tools/SDK are required for developing a Node.js application on any platform,

1. Node.js

2. Node Package Manager (NPM)

- NPM (Node Package Manager) is included in Node.js installation

3. IDE (Integrated Development Environment) or TextEditor like Visual Code Editor

• Node.js official web site https://nodejs.org

– It will automatically detect OS and display download link as per your Operating System.

– Once the Node.js installed , can verify it by opening the command prompt and typing node -v.

– If Node.js is installed successfully then it will display the version of the Node.js

25 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
• Node.js comes with virtual environment called REPL (i.e Node shell).

• REPL stands for Read-Eval-Print-Loop.

• It is a quick and easy way to test simple Node.js/JavaScript code.

• To launch the REPL (Node shell),

– open command prompt (in Windows) or terminal (in Mac or UNIX/Linux)

– type node

– It will change the prompt to >.

26 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
Simple Expression

Let's try a simple mathematics at the Node.js REPL command prompt:

27 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
Use Variables

• We can make use of variables to store values and print later like any conventional script.

– If var keyword is not used, then the value is stored in the variable and printed.

– If var keyword is used, then the value is stored but not printed.

– We can print variables using console.log()

28 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
Multiline Expression

• Node REPL supports multiline expression similar to JavaScript.

Let's check the following do-while loop in action:

29 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
To execute an external JavaScript file

• Done by executing the node fileName command.

• For example, the following runs mynodejs-app.js on the command prompt/terminal and displays the
result.

Visual Code Editor

Command prompt

30 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
Stopping REPL
• To exit from the REPL terminal, press Ctrl + C twice or write .exit and press Enter.

31 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Console/REPL
REPL Commands
REPL Command Description
ctrl + c Terminate the current command.
ctrl + c (twice) Exit from the REPL.
ctrl + d Exit from the REPL.
.break Exit from multiline expression.
.clear Exit from multiline expression.
.help Display help on all the commands
tab Keys Display the list of all commands.
Up/Down Keys See previous commands applied in REPL.

.save filename Save current Node REPL session to a file.

.load filename Load the specified file in the current Node REPL
session.
32 Node.js | © Smartcliff | Internal | Version 1.0
Javascript in the Desktop with NodeJS

Node.js Fundamentals
• Node.js supports JavaScript.

– So, JavaScript syntax on Node.js is similar to the browser's JavaScript syntax.

• Primitive Types

• Node.js includes following primitive types:

– String

– Number

– Boolean

– Undefined

– Null

– RegExp

• Everything else is an object in Node.js.


33 Node.js | © Smartcliff | Internal | Version 1.0
Javascript in the Desktop with NodeJS

Node.js Fundamentals
• Loose Typing

– JavaScript in Node.js supports loose typing like the browser's JavaScript.

– Use var, const or let keyword to declare a variable of any type.

• Object Literal

– Object literal syntax is same as browser's JavaScript.

var obj = {
authorName: 'Ryan Dahl',
language: 'Node.js'
}

34 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Fundamentals
• Functions

– Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript.

– A function can have attributes and properties also.

Filename: app.js
function Display(x) {
console.log(x);
}
Display(100);

35 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Fundamentals
• Arrow Functions

– Arrow functions allow us to write shorter function syntax:


Filename: functiondemo.js
function sum(a,b) {
return a+b;
}
var s = sum(3,4);
console.log("Normal Function: " + s);

var sum = (a,b) => {


return a+b;
}
var s = sum(3,4);
console.log("Arrow Function: " + s);

36 Node.js | © Smartcliff | Internal | Version 1.0


Javascript in the Desktop with NodeJS

Node.js Local and Global Scope

• Node's JavaScript is different from browser's JavaScript when it comes to global scope.

• In the browser's JavaScript,

– variables declared without var keyword become global.

• In Node.js, everything becomes local by default.

• In a browser, global scope is the window object.

– In Node.js, global object represents the global scope.

37 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager
(NPM)
Please download pictures in
suitable size here and insert them
by clicking the symbol above.

38 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

Installing NPM:

To install NPM, it is required to install Node.js as NPM gets installed with Node.js automatically.

Checking and updating npm version:

• Version of npm installed on system can be checked using the syntax

npm –v

• Older version of NPM can be updated to the latest version using the following command.

npm install npm@latest –g

As npm is a global package, -g flag is used to update it globally.

39 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)


Creating a Node Project: {

"name": "notes-app",
• To create a Node project, npm init is used in the folder
"version": "1.0.0",
in which user want to create project.
"description": "",

• The npm command line will ask a number of questions "main": "app.js",

"scripts": {
like name, license, scripts, description, author,
"test": "echo \"Error: no test specified\"
keywords, version, main file etc.
&& exit 1"

• After npm is done creating the project, },

"author": "",
a package.json file will be visible in project folder as a
"license": "ISC",
proof that the project has been initialized.
}
40 Node.js | © Smartcliff | Internal | Version 1.0
Node Package Manager(NPM)

Node Package Manager(NPM)


Installing Packages:

• After creating the project, next step is to incorporate the packages and modules to be used in the Node
Project.

• To install packages and modules in the project (locally) the following syntax:

npm install <package_name>

• NPM can also install packages globally so that all the node.js application on that computer can import
and use the installed packages.

• NPM installs global packages into /<User>/local/lib/node_modules folder.

• Apply -g in the install command to install package globally. The syntax is

npm install -g <package_name>

41 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)


Example: To install validator package, the syntax is:

npm install validator

This syntax does three important things:

• First, it creates a node_modules directory.

– npm uses this directory to store all the code for the npm modules that have installed.

• Second, npm adds the module as a dependency by listing it in the dependencies property in package.json.

– This allows to track and manage the module that have installed.

• Third, npm creates a package-lock.json file.

– This includes detailed information about the modules that have installed which helps keep things fast
and secure

42 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

Controlling where the package gets installed:

• To install a package and simultaneously save it in package.json file (in case using Node.js), add –

save flag.

• The –save flag is default in npm install command so it is equal to npm install package_name command.

npm install validator –save

Importing an npm Module:

• npm modules can be imported into your script using require() function.

• To load in an npm module, pass the npm module name to require.

43 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

Filename: validator.js

const validator = require('validator')

console.log(validator.isURL('https/mead.io')) // Print: false

The script above uses require() to load in validator.

The script then uses the isURL() function provided by validator to check if a given string contains a
valid URL.

44 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

Update Package:

• To update the package installed locally, follow the below syntax:

npm update <package name>

Uninstalling Packages:

• To uninstall packages using npm, follow the below syntax:

npm uninstall <package_name>

• To uninstall global packages, follow the below syntax:

npm uninstall <package_name> -g

45 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

Global npm Modules and nodemon

• nodemon is a tool that helps develop node.js based applications by automatically restarting the node

application when file changes in the directory are detected.

• nodemon does not require any additional changes to the code or method of development.

• nodemon is a replacement wrapper for node.

• To use nodemon, replace the word node on the command line when executing the script.

46 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

• Installation: nodemon will be installed globally to our system path using below syntax:

npm install -g nodemon

• It can also install nodemon as a development dependency:

npm install --save-dev nodemon

• Usage : nodemon wraps the application, so that we can pass all the arguments we would normally
pass to our app:

nodemon [your node app]

47 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)


Lets write an example index.js file that outputs the message: 'Welcome to Node.js!'

Filename: index.js
const http = require("http");
const server = http.createServer((req,res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to Node.js!');
res.end();
});
server.listen(3000);

Run index.js file using the command: nodemon index.js

48 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)


Lets write an example index.js file that outputs the message: 'Welcome to Node.js!'

49 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)


The terminal output will display:

While nodemon is still running, let’s make a change to the index.js file.
Add a message: ‘Node.js is an open-source server side runtime environment.’.

50 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)


Filename: index.js
const http = require("http");
const server = http.createServer((req,res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Welcome to Node.js!');
res.write(‘<br>Node.js is an open-source server side runtime environment.’);
res.end();
});
server.listen(3000);

The terminal output will display:

51 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

• The terminal output from the Node.js app is displaying the new changes.

• We can restart the process at any time by typing rs and hitting ENTER.

• Alternatively, nodemon will also look for a main file specified in our project’s package.json file:

Filename: package.json
{
// ...
"main": “index.js",
// ...
}

52 Node.js | © Smartcliff | Internal | Version 1.0


Node Package Manager(NPM)

Node Package Manager(NPM)

• If a main file is not specified, nodemon will search for a start script:

Filename: package.json
{
// ...
"scripts": {
"start": "node index.js"
},
// ...
}

• Once we make the changes to package.json, we can then call nodemon to start the example app in

watch mode without having to pass in index.js.

53 Node.js | © Smartcliff | Internal | Version 1.0


Node.js Web Server

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

54 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Node.js Web Server

• Node.js is an open source server environment.

• Node.js uses JavaScript on the server.

– The task of a web server is to open a file on the server and return the content to the client.

• To access web pages of any web application, we need a web server.

• The web server will handle all the http requests for the web application

– e.g IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web
applications.

• Node.js provides capabilities to create our own web server which will handle HTTP requests
asynchronously.

• We can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web
server.
55 Node.js | © Smartcliff | Internal | Version 1.0
NodeJS Web Server

Node.js Web Server

• Node.js makes it easy to create a simple web server that processes incoming requests

asynchronously.

• Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text

Transfer Protocol (HTTP).

• The HTTP module can create an HTTP server that listens to server ports and gives a response back to

the client.

56 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Create Node.js Web Server


The following example is a simple Node.js web server contained in server.js file.

Filename: http_server.js

var http = require('http'); // 1 - Import Node.js core module

var server = http.createServer(function (req, res) { // 2 - creating server

//handle incomming requests here..

});

server.listen(3000); // 3 - listen for any incoming requests

console.log('Node.js web server at port 3000 is running..')

57 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Create Node.js Web Server

In the given example,

• We import the http module using require() function.

• The http module is a core module of Node.js, so no need to install it using NPM.

• The next step is to call createServer() method of http and specify callback function with request
and response parameter.

• Finally, call listen() method of server object which was returned from createServer() method with port
number, to start listening to incoming requests on port 3000.

• We can specify any unused port here.

58 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Create Node.js Web Server

• Run the command node server.js in the terminal.


• The terminal output will display

59 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Handling HTTP Request

• The http.createServer() method includes request and response parameters which is supplied by

Node.js.

• The request object can be used to get information about the current HTTP request e.g., url, request

header, and data.

• The response object can be used to send a response for a current HTTP request.

60 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Handling HTTP Request


The following example demonstrates handling HTTP request and response in Node.js.
Filename: server.js
var http = require('http'); // Import Node.js core module
var server = http.createServer(function (req, res) { //create web server
if (req.url == '/') { //check the URL of the current request

// set response header


res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content


res.write('<html><body><p>This is Home page.</p></body></html>');
res.end();
}
else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is Admin page.</p></body></html>');
res.end();
}
61 Node.js | © Smartcliff | Internal | Version 1.0
NodeJS Web Server

Handling HTTP Request

else if (req.url == "/employee") {


res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is Employee page.</p></body></html>');
res.end();
}
else
res.end('Invalid Request!');
});
server.listen(3000); // listen for any incoming requests
console.log('Node.js web server at port 3000 is running..')

62 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Handling HTTP Request

In the given example,

• req.url is used to check the url of the current request and based on that it sends the response.

• To send a response, first it sets the response header using writeHead() method and then writes a

string as a response body using write() method.

• Finally, Node.js web server sends the response using end() method.

63 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Handling HTTP Request

• Run the command node server.js in the terminal.


• The terminal output will display

64 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Handling HTTP Request

• Point the browser to http://localhost:3000 and see the Node.js Web Server Response.

/home url is not specified. So it displays "Invalid


Request" for all requests other than the
specified URLs.

65 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Sending JSON Response


The following example demonstrates how to serve JSON response from the Node.js web server.
Filename: server_json.js
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == '/data') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Hello World"}));
res.end();
}
});
server.listen(3000);
console.log('Node.js web server at port 3000 is running..')

66 Node.js | © Smartcliff | Internal | Version 1.0


NodeJS Web Server

Sending JSON Response


• Run the command node server.js in the terminal.
• The terminal output will display

• Point the browser to http://localhost:3000/data and see the Node.js Web Server Response.

JSON response from the


Node.js web server
67 Node.js | © Smartcliff | Internal | Version 1.0
Frameworks for NodeJS

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

68 Node.js | © Smartcliff | Internal | Version 1.0


Frameworks for NodeJS

Node Framework

• A framework is a collection of various libraries and tools that are required in the development

process of a software application.

• It acts as a base on which different software applications can be developed.

• A node framework is a workspace platform that supports the use of Node.js and which allows

developers to use JavaScript for developing front end as well as the back end of an application.

• Node frameworks are a wide collection of frameworks built on Node and that extend its properties

and functionalities further.

69 Node.js | © Smartcliff | Internal | Version 1.0


Frameworks for NodeJS

Node Framework

Benefits of Node Framework

• Productivity

• Scalability

• Speed

• Same Languages for Front-end and Back-end

• Maintaining Code standards across a team

70 Node.js | © Smartcliff | Internal | Version 1.0


Frameworks for NodeJS

Frameworks for NodeJS

• There are various third party open-source frameworks available in Node Package Manager which
makes Node.js application development faster and easy.

• We can choose an appropriate framework as per our application requirements.

• The following table lists frameworks for Node.js.

Open-Source
Framework Description
Express.js Express is a minimal and flexible Node.js web application framework that provides a
robust set of features for web and mobile applications. This is the most popular
framework as of now for Node.js.
Geddy Geddy is a simple, structured web application framework for Node.js based on MVC
architecture.
Hapi.js Hapi is a rich Node.js framework for building applications and services.
71 Node.js | © Smartcliff | Internal | Version 1.0
Frameworks for NodeJS

Frameworks for NodeJS


• The following table lists frameworks for Node.js.
Open-Source
Framework Description
Locomotive Locomotive is MVC web application framework for Node.js. It supports MVC patterns,
RESTful routes, and convention over configuration, while integrating seamlessly with any
database and template engine. Locomotive builds on Express, preserving the power and
simplicity you've come to expect from Node.
Koa Koa is a new web framework designed by the team behind Express, which aims to be a
smaller, more expressive, and more robust foundation for web applications and APIs.

Total.js Totaljs is free web application framework for building web sites and web applications
using JavaScript, HTML and CSS on Node.js
Keystone Keystone is the open source framework for developing database-driven websites,
applications and APIs in Node.js. Built on Express and MongoDB.
72 Node.js | © Smartcliff | Internal | Version 1.0
Frameworks for NodeJS

Frameworks for NodeJS


• The following table lists frameworks for Node.js.
Open-Source
Framework Description
Derbyjs Derby support single-page apps that have a full MVC structure, including a model
provided by Racer, a template and styles based view, and controller code with application
logic and routes.
Sails.js Sails makes it easy to build custom, enterprise-grade Node.js apps. It is designed to
emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for
the requirements of modern apps: data-driven APIs with a scalable, service-oriented
architecture. It's especially good for building chat, realtime dashboards, or multiplayer
games; but you can use it for any web application project - top to bottom.
Meteor Meteor is a complete open source platform for building web and mobile apps in pure
JavaScript.

73 Node.js | © Smartcliff | Internal | Version 1.0


Frameworks for NodeJS

Frameworks for NodeJS


• The following table lists frameworks for Node.js.
Open-Source
Framework Description

Mojito This HTML5 framework for the browser and server from Yahoo offers direct MVC access
to the server database through the local routines. One clever feature allows the code to
migrate. If the client can't run JavaScript for some reason, Mojito will run it on the server -
- a convenient way to handle very thin clients.

Restify Restify is a node.js module built specifically to enable you to build correct REST web
services.
Frisby Frisby is a REST API testing framework built on node.js and Jasmine that makes testing
API endpoints easy, fast, and fun.
Chocolate.js Chocolate is a simple webapp framework built on Node.js using Coffeescript.

74 Node.js | © Smartcliff | Internal | Version 1.0


Frameworks for NodeJS

Frameworks for NodeJS


• The following table lists frameworks for Node.js.
Open-Source
Framework Description
ActionHero actionhero.js is a multi-transport Node.JS API Server with integrated cluster
capabilities and delayed tasks.

Mean.js It is an added Node.js framework mounted on the top of Express. It helps you create
secure, robust, and maintainable production web applications using MongoDB,
Express, AngularJS, and Node.js.

NestJS It is a Node.js framework used for building server-side applications that are efficient in
every way. Apart from using JavaScript, it also supports TypeScript along with certain
elements of Functional Programming (FP), Object-Oriented Programming (OOP) and
Function Reactive Programming (FRP).

75 Node.js | © Smartcliff | Internal | Version 1.0


Frameworks for NodeJS

Frameworks for NodeJS


• The following table lists frameworks for Node.js.
Open-Source
Framework Description
Feathers.js It is a simplistic real-time framework mounted on the top of Express.js for writing
advanced web applications. It effortlessly combines with any client-side framework.
With the help of Feathers framework, you will discover and acquire all the modern
coding protocols by default.

AdonisJS It is a Node.js MVC framework that provides the ability to write web applications by
using less code and focuses on being a stable framework in the colony of Node
frameworks. One important factor about AdonisJS is that it contains a number of test
modules that help to improve the efficiency of one’s code.

Loopback Loopback is an open-source Node.js API framework.

76 Node.js | © Smartcliff | Internal | Version 1.0


Introduction to
Express.js
Please download pictures in
suitable size here and insert them
by clicking the symbol above.

77 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Getting started with Express.js

• Express.js is a Node js web application server framework.

• Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation and

numerous open source contributors.

• It provides various features that make web application development fast and easy which otherwise takes

more time using only Node.js.

• It is specifically designed for building single-page, multi-page, and hybrid web applications.

• The Express.js framework makes it very easy to develop an application which can be used to handle

multiple types of requests like the GET, PUT, and POST and DELETE requests.

78 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Getting started with Express.js

• Express.js is based on the Node.js middleware module called connect which in turn uses http module.

• So, any middleware which is based on connect will also work with Express.js.

Express.js

connect

http

Node.js

79 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Advantages of Express.js

• Makes Node.js web application development fast and easy.

• Easy to configure and customize.

• Allows to define routes of your application based on HTTP methods and URLs.

• Includes various middleware modules which can use to perform additional tasks on request and
response.

• Easy to integrate with different template engines like Jade, Vash, EJS etc.

• Allows to define an error handling middleware.

• Easy to serve static files and resources of our application.

• Allows to create REST API server.

• Easy to connect with databases such as MongoDB, Redis, MySQL

80 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Install Express.js

• Express.js can be installed using npm.


• The following command will install latest version of express.js globally on the machine so that every
Node.js application on the machine can use it. (Location: %Users%\1377\AppData\Roaming\npm)

npm install -g express

• The following command will install latest version of express.js local to the project folder.

E:\_Smart\MERN\Expressjs> npm install express

• It will update the package.json file by specifying express.js dependency.


• npm creates a package-lock.json file that includes detailed information about the modules that
have installed which helps keep things fast and secure.

81 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Install Express.js
• Figure shows express is added under dependencies section,

• Note: use “npm uninstall express” will remove express and updates in package.json file.

82 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Install Express.js

• Now package.json file set up, we will further install Express.


• To install Express and add it to our package.json file, use the following command:

npm install express

• To make our development process a lot easier, we will install a tool from npm, nodemon.
• This tool restarts our server as soon as we make a change in any of our files, otherwise we need to
restart the server manually after each file modification.
• To install nodemon, use the following command −

npm install -g nodemon

83 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Basic Express.js app

• Lets create a file called app.js and type the following in it.

Filename: app.js
const express = require('express’); //imported Express.js module using require()
function
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {


res.send('Hello, Geeks!');
});

app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});

84 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Basic Express.js app

• Run the command nodemon app.js in the terminal.

• This will start the server. To test this app, open the browser and go to http://localhost:3000 and a
message will be displayed as in the following screenshot.

85 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Basic Express.js app


How the App Works?

• The first line imports Express in our file, we have access to it through the variable ‘express’.

• We use it to create an application and assign it to var app.

• app.get(route, callback) function tells what to do when a get request at the given route is called.

– The callback function has 2 parameters, request(req) and response(res).

– The request object(req) represents the HTTP request and has properties for the request query string,

parameters, body, HTTP headers, etc.

– Similarly, the response object represents the HTTP response that the Express app sends when it
receives an HTTP request.

86 Express.js | © Smartcliff | Internal | Version 1.0


Introduction to Express.js

Basic Express.js app


How the App Works?

• res.send() function takes an object as input and it sends this to the requesting client. Here we are

sending the string "Hello, Geeks!".

• app.listen(port, [host], [backlog], [callback]]) function binds and listens for connections on the

specified host and port. Port is the only required parameter here.

87 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP
Methods
Please download pictures in
suitable size here and insert them
by clicking the symbol above.

88 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Routing
• Routing refers to determining how an application responds to a client request to a particular endpoint,
which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

• Each route can have one or more handler functions, which are executed when the route is matched.

• Route definition takes the following structure:

app.METHOD( PATH, HANDLER)

– app is an instance of express.

– METHOD is an HTTP request method, in lowercase get, post, put, delete.

– PATH is a path on the server.

– HANDLER is the callback function that is executed when the matching request type is found on the relevant
route.

89 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

HTTP Methods
The HTTP method is supplied in the request and specifies the operation that the client has
requested. The following table lists the most used HTTP methods −
Method Description
GET The GET method requests a representation of the specified resource. Requests
using GET should only retrieve data and should have no other effect.

POST The POST method requests that the server accept the data enclosed in the
request as a new object/entity of the resource identified by the URI.

PUT The PUT method requests that the server accept the data enclosed in the request
as a modification to existing object identified by the URI.
If it does not exist then the PUT method should create one.

DELETE The DELETE method requests that the server delete the specified resource.

90 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Routing - GET route


• Lets create a file called get_route.js and use app object to define GET route

Filename: get_route.js
var express = require('express');
var app = express();
app.get('/hello', function(req, res){
res.send("Hello World!");
});
app.listen(3000);

91 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Routing - Example
• If we run our application and go to localhost:3000/hello, the server receives a get request at
route "/hello", our Express app executes the callback function attached to this route and
sends "Hello World!" as the response.

92 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Routing - GET route


• app.get() is a function that tells the server what to do when a get request at the given route is called.

• It has a callback function (req, res) that listen to the incoming request req object and respond
accordingly using res response object.

• Both req and res are made available to us by the Express framework.

• The req object represents the HTTP request and has properties for the request query string,
parameters, body, and HTTP headers.

• The res object represents the HTTP response that an Express app sends when it gets an HTTP
request.

• In our case, we are sending a text Hello World whenever a request is made to the route /.

• Lastly, app.listen() is the function that starts a port and host, in our case the localhost for the connections
to listen to incoming requests from a client. We can define the port number such as 3000.
93 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods

Request and Response Object Properties

94 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

URL Building: Dynamic Routing


• Dynamic Routing allows us to pass parameters and values in routes on the basis of which the server
processes our request and sends back the response.

• This is not fixed or static.

• The value of parameter can be changed.

• For understanding purpose, let’s see Facebook profile link https://fb.com/itsaareez1 where ‘itsaareez1’ is
profile’s username.

• Every user has a unique username so, this value will vary according to user. This is dynamic routing.

• We use : to make any route dynamic

95 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

URL Building: Dynamic Routing


Example :

Filename: dynamic_route.js
var express = require('express');
var app = express();

app.get('/:id', function(req, res){


res.send('The id you specified is ' +
req.params.id);
});
app.listen(3000);

96 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

URL Building: Dynamic Routing


Run the express app using command nodemon dynamic_route.js

To test this go to http://localhost:3000/123. The following response will be displayed.

97 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

URL Building: Dynamic Routing


• We can replace '123' in the URL with anything else and the change will reflect in the response. A more
complex example of the above is

• Example

Filename: dynamic_route2.js
var express = require('express');
var app = express();

app.get('/things/:name/:id', function(req, res) {


res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(3000);

98 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

URL Building: Dynamic Routing


Run the express app using command nodemon dynamic_route2.js

To test the above code, go to http://localhost:3000/things/express/12345.

We can use the req.params object to access all the parameters you pass in the url. Note that the above 2
are different paths. They will never overlap. Also if you want to execute code when you get '/things' then
you need to define it separately.

99 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Configure Routes

• A special method, all, is provided by Express to handle all types of http methods at a particular route

using the same function.

• Like if we have POST, GET, PUT, DELETE, etc, request made to any specific route, let say /user, so

instead to defining different API’s like app.post(‘/user’), app.get(‘/user’), etc, we can define single

API app.all(‘/user’) which will accept all type of HTTP request.

app.all( path, callback )

– Path: It is the path for which the middleware function is called.

– Callback is the function executed when the route is matched.

100 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Configure Routes
Filename: app.js
var express = require('express');
var app = express();
var PORT = 3000;
app.all('/user', function (req, res) {
console.log('USER API CALLED');
res.send('<html><body><h1>Hello World</h1></body></html>');
});

app.listen(PORT, function(){
console.log("Server listening on PORT", PORT);
});

101 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Configure Routes
• Run the command nodemon app.js and point the browser to http://localhost:3000 and see the following
result.

102 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Route parameters
• Route parameters are named URL segments that are used to capture the values specified at their position in
the URL. The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).

• The captured values are populated in the req.params object, with the name of the route parameter specified in
the path as their respective keys.

Route path: /users/:userId/books/:bookId


Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }

• To define routes with route parameters, simply specify the route parameters in the path of the route:

app.get('/users/:userId/books/:bookId', function(req, res) {


res.send(req.params)
})

103 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Route parameters
• Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route parameters
for useful purposes.

Route path: /flights/:from-:to


Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }

Route path: /plantae/:genus.:species


Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }

104 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Route parameters
• To have more control over the exact string that can be matched by a route parameter, we can append a
regular expression in parentheses (()):

Route path: /user/:userId(\d+)


Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

• Because the regular expression is usually part of a literal string, be sure to escape any \ characters with
an additional backslash, for example \\d+.

105 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Route parameters
Filename: route-params.js
var express = require('express');
var app = express();
app.get('/user/:userId/books/:bookid', (req, res) => {
req.params; // { userId: '42' }
res.json(req.params);
});
app.get('/flights/:from-:to', (req, res) => {
req.params; // { "from": "LAX", "to": "SFO" }
res.json(req.params);
});

106 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Route parameters
app.get('/plantae/:genus.:species', (req, res) => {
req.params; // { "genus": "Prunus", "species": "persica" }
res.json(req.params);
});
app.get('/user/:userId', (req, res) => {
req.params; // {"userId": "42"}
res.json(req.params);
});
var server = app.listen(3000, function () {
console.log('Node server is running..');
});

107 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Handle POST Request


• To handle HTTP POST request and get data from the submitted form.

• First, create index.html file in the root folder of your application and write the following HTML code in it.
Filename: index.html
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="/submit-data" method="post">
First Name: <input name="firstName" type="text" /> <br />
Last Name: <input name="lastName" type="text" /> <br />
<input type="submit" /> </form> </body> </html>
108 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods

Handle POST Request

Body Parser

• To handle HTTP POST request in Express.js version 4 and above, we need to install middleware module

called body-parser.

• The middleware was a part of Express.js earlier but now we have to install it separately.

• This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP

POST request. Install body-parser using NPM as shown below.

npm install body-parser --save

109 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Handle POST Request


Import body-parser and get the POST request data as shown below.
Filename: post_route.js
var express = require('express');
var app = express(); In this example,
var bodyParser = require("body-parser"); • POST data can be accessed using
app.use ( bodyParser.urlencoded ( { extended: false }));
req.body.
app.get('/', function (req, res) {
res.sendFile('E:/_Smar/MERN/Expressjs/index.html');
• The req.body is an object that
}); includes properties for each submitted

app.post('/submit-data', function (req, res) { form. Index.html contains firstName


var name = req.body.firstName + ' ' + req.body.lastName; and lastName input types, so we can
res.send(name + ' Submitted Successfully!'); access it using req.body.firstName
});
and req.body.lastName.
var server = app.listen(3000, function () {
console.log('Node server is running..');
});
110 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods

Handle POST Request


• Run the command nodemon post_route.js and point the browser to http://localhost:3000 and see the
following result.

111 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Handle POST Request


• Fill the First Name and Last Name in the above example and click on submit.
• For example, enter “Mark" in First Name textbox and “Andrew" in Last Name textbox and click the submit
button. The following result is displayed.

112 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Routers

• Defining routes in the same file is very tedious to maintain. To separate the routes from our main index.js
file, we will use express.Router. Create a new file called books.js and type the following in it.

Filename: books.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.send('GET random book.');
});
router.post('/', function(req, res){
res.send(' Add a book.');
});
//export this router to use in our index.js
module.exports = router;
113 Express.js | © Smartcliff | Internal | Version 1.0
Routing and HTTP Methods

Routers

• Now to use this router in our index.js, type the following before the app.listen function call.

Filename: index.js
In this example,
var express = require(‘Express');
• The app.use function call on
var app = express();
route '/books' attaches
var PORT = 3000;
the books router with this route.
var books = require('./books.js');
• Now whatever requests our app
//both index.js and books.js should be in same directory
gets at the '/books', will be
app.use('/books', books);
app.listen(PORT, function(err){ handled by our things.js router.

if (err) console.log(err); • The '/' route in books.js is

console.log("Server listening on PORT", PORT); actually a subroute of '/books'.


});

114 Express.js | © Smartcliff | Internal | Version 1.0


Routing and HTTP Methods

Routers
• Run the command nodemon index.js and point the browser to http://localhost:3000 and see the following
result.

115 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

116 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

Template Engine

• A template engine facilitates to use static template files in the applications.

• At runtime, it replaces variables in a template file with actual values, and transforms the template into an
HTML file sent to the client.

• So this approach is preferred to design HTML pages easily.

• There are number of template engines available some of them are given below:-
– EJS
– Pug (formerly known as jade)
– Vash
– Mustache
– Dust.js
– Nunjucks
– Handlebars

117 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

Using template engines with Express

• Template engine makes us able to use static template files in our application.

• To render template files we have to set the following application setting properties:

• Views: It specifies a directory where the template files are located.

For example: app.set('views', './views').

• view engine: It specifies the template engine that you use.

For example, to use the Pug template engine: app.set('view engine', 'pug')

118 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

PUG template engine

Integrating PUG into Express

• First, install the pug package from npm:

npm i pug

• Create a folder named “Views” in project’s root directory Because by default Express.js searches all the
views (templates) in the views folder under the root folder.

• If we don’t want your folder to be named as views we can change name using views property in express.

• Eg : the name of your folder is myviews then in our main file in this case app.js we write
app.set(‘views’,./myviews);

• All the templates file are saved with template engine’s extension and in views folder. Here we are using
pug so all templates are saved with .ejs extension in views folder.

119 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

PUG template engine

• -
Filename:index.pug
html
- var demo = "Thanks for watching"
head
title Learn Express JS
style
include index.css
body
h1.demo1 Welcome to Template Engine
p#demo2 Join with me, to learn Template engine
a(href="https://smartcliff.in/") Click Here
ul
each val in ['MongoDB','Express','Angular','NodeJS']
li= val

120 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

PUG template engine

• -
Filename:index.pug
div
input(
type ="text"
placeholder ="Enter your Name"
)
div
h1=Quotes
h2=Topic
div
h1(style={color:'red'}) Hello #{demo}});

121 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

PUG template engine

• -
Filename:index.css
.demo1{
color: blueviolet;
}
#demo2{
color: brown;
}
.demo3{
color: red;
}

122 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

PUG template engine

• -
Filename:app.js
var express=require('express');
var app=express();
app.set('view engine','pug');
app.set('views','./views')
app.get('/',function(req,res){
res.render('index',{
Quotes : "Designer can design everything",
Topic : "MEAN Stack"
});
});
app.listen(3000);
123 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

PUG template engine

• output

124 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

• EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.

• EJS is much more similar to HTML than Pug is, retaining the usual method of opening and closing tags
as well as specifying attributes.

• Variables are declared using angle brackets and the percent sign in this manner: <%= name %>.

125 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

Integrating EJS into Express

• First, install the ejs package from npm:

npm i ejs

• Create a folder named “Views” in project’s root directory Because by default Express.js searches all the
views (templates) in the views folder under the root folder.

• If we don’t want your folder to be named as views we can change name using views property in express.

• Eg : the name of your folder is myviews then in our main file in this case app.js we write
app.set(‘views’,./myviews);

• All the templates file are saved with template engine’s extension and in views folder. Here we are using
EJS so all templates are saved with .ejs extension in views folder.

126 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

• EJS files are simple to write because in this file we write simple HTML and write logic, backend variables

between these tags:-

<% %> ( to write logics )

<%= %> ( when we want to display content use this )

<%- %> ( display raw HTML )

127 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

• For demonstration purpose, we have two files one is main JS file i.e. app.js , which creates a server and
one template file( display.ejs ).

Filename:app.js
// To create a basic server like
var express = require("express"); //requiring express module
var app = express(); //creating express instance

//To send templates to frontend, first we set the view engine as follows:
app.set("view engine","ejs");

app.get("/", function(req, res) {


res.send("hello");
});

app.listen(3000, function() {
console.log("Node server is running..");
});
128 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

EJS template engine

• After setting the view engine we create a simple display.ejs file in view folder with a simple ‘hello user’
message in it.

Filename:display.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>templates</title>
</head>
<body>
<p>Hello User</p>
</body>
</html>

129 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


• Now to send the file to frontend we have a function called i.e. res.render() , it renders a view and sends
the rendered HTML string to the client.

• To render our file in previous code we replace res.send(“hello”); with res.render(‘display’) ;


Filename:app.js
// To create a basic server like
var express = require("express"); //requiring express module
var app = express(); //creating express instance

//To send templates to frontend, first we set the view engine as follows:
app.set("view engine","ejs");

app.get("/", function(req, res) {


res.render('display');
});
app.listen(3000, function() {
console.log("Node server is running..");
});
130 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

EJS template engine


• Run the following code as “nodemon app.js” in terminal and point to browser to http://localhost:3000 and
see the message “Hello User” will be printed

131 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


Sending variables to EJS and show on frontend

• If we want to send data from backend and use it in EJS file we can do this in the following manner:-

• Here instead of user in our display.ejs file I want to specify the name of the user. We can send data
where we are rendering the file.

• Eg:- res.render(‘display’,{variable_name:’value’});

• Say the username is ‘Alice’ then our code will be:-

res.render('display',{user:'Alice'});

• And to display this on front end we write this user variable inside <%= %> like this:-

<p>Hello <%= user%></p>


• Now restart the server and run the code again and on refreshing the page you will see Hello Alice instead
of Hello User.

132 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

Filename:display.ejs Filename:app.js
<!DOCTYPE html> // To create a basic server like
<html lang="en"> var express = require("express"); //requiring
<head> express module
<meta charset="UTF-8"> var app = express(); //creating express instance
<meta name="viewport"
content="width=device-width, initial- //To send templates to frontend, first we set the
scale=1.0"> view engine as follows:
<meta http-equiv="X-UA-Compatible" app.set("view engine","ejs");
content="ie=edge">
<title>templates</title> app.get("/", function(req, res) {
</head> res.render('display',{user:'Alice'});
<body> });
<p>Hello <%= user%></p> app.listen(3000, function() {
</body> console.log("Node server is running..");
</html> });

133 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


• Run the command as “nodemon app.js” in terminal and point to browser to http://localhost:3000 and see
the message “Hello User” will be printed

134 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


Filename:app_authors.js
Sending Arrays or Objects(JSON data) // example for Sending Arrays or Objects(JSON data)
var express = require("express");
• We can send any sort of data to the var app = express(); /
frontend. Suppose if we have a JSON data app.set("view engine","ejs");
var authors = [
having an array named authors[] of author {
name: 'Andrew',
object having name and article, and I want article: 'node.js',
to display it on frontend via a list, I can send },
{
an array to EJS and then loop through it name: 'Brad',
article: 'express.js',
and display the data. For this follow the },
given code in app.js:- {
name: 'John',
article: 'mongoose',
},
]
app.get('/authors', function (req, res) {
res.render('displayAuthors', { authors })
})
135 Express.js | © Smartcliff | Internal | Version 1.0 app.listen(3000);
Express.js Templating

EJS template engine


• Now to access the author array in EJS follow the given EJS code:-

Filename:display_author.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h3>Name Of Authors</h3>
<ul>
<% authors.forEach(function(author){ %> <!-- looping through authors array -->
<li>
<%= author.name %>
</li>
<% }) %> </ul></body></html>
136 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

EJS template engine


• Here In the above EJS code, we have used a forEach loop to iterate through “authors” array and to
access data of authors array one by one.

• Save app.js and display.ejs with the following code and then run the code, now as we refresh the web
page(http://localhost:3000/authors) you will see the following output.

137 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

Serving static files in Express

• To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in
middleware function in Express.

• The function signature is: express.static(root, [options])


• The root argument specifies the root directory from which to serve static assets.

• For example, use the following code to serve images, CSS files,

and JavaScript files in a directory named public:

app.use(express.static('public'))

138 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine

• For static files, we create a folder with name such as ‘public’. When we set our static files folder as
‘public’ using express.static middleware, all the static files will be served from this public folder itself.

• Suppose, we create a route to display a frontend page, with an image, as shown below:

Filename:app_image.js
var express = require("express");
var app = express();
app.set("view engine","ejs");
app.use(express.static('public'))
app.get('/image', (req, res) => {
res.render('displayImage')
}) app.listen(3000);

139 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


• For demonstration purpose, let’s take a jpg image file named ‘logo.jpg’ in our public folder. And a
displayImage.ejs file in our view folder which has the following code in it :

Filename:displayimage.ejs
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>SmartCliff Image Below</h1>
<img src=“logo.png" alt=“LOGO" />
</body> </html>
• Notice the image element source to logo.png . Since you’ve served the public directory through Express,
you can add the file name as your image source’s value.
140 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

EJS template engine


• Run the command as “nodemon app_image.js” in terminal and point to browser to http://localhost:3000
/image and see the result

141 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


Multiple Static Directories

• We can also set multiple static assets directories using the following program −

var express = require('express');


var app = express();

app.use(express.static('public'));
app.use(express.static('images'));

app.listen(3000);

142 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

EJS template engine


Virtual Path Prefix

• We can also provide a path prefix for serving static files. For example, if you want to provide a path prefix
like '/static', you need to include the following code in our .js file −

var express = require('express');


var app = express();
app.use('/static', express.static('public'));
app.listen(3000);

• Now whenever we need to include a file, for example, a script file called .ejs residing in our public
directory, use the following script tag −

<script src = "/static/main.js" />

• This technique can come in handy when providing multiple directories as static files. These prefixes can
help distinguish between multiple directories.
143 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

Form Handling in Express

• In express, to handle form submission, we use ‘body-parser’ to parse the body received in our route

request of form submission.

• A simple demonstration of form handling using a simple form page rendered through GET request on

route ‘/formPage’ and post request on route ‘/form-submit’

144 Express.js | © Smartcliff | Internal | Version 1.0


Express.js Templating

Form Handling in Express


• Frontend

Filename: formPage.ejs Page : <%= heading %>


<!DOCTYPE html> <form method="POST" action="/submit-form">
<html lang="en"> <label for="name">Name:</label><br />
<head> <input type="text" id="name" name="name" /><br
<meta charset="UTF-8" /> /><br />
<meta http-equiv="X-UA-Compatible" <label for="email">Email:</label><br />
content="IE=edge" /> <input type="email" id="email" name="email" /><br
<meta name="viewport" /><br />
content="width=device-width, initial-scale=1.0" /> <label for="password">Password:</label><br />
<title>Form Page</title> <input type="password" id="password"
</head> name="password" /><br /><br />
<body> <input type="submit" value="Submit" />
</form></body></html>
145 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

Form Handling in Express


• Backend

Filename: form.js
var express = require("express"); app.post('/submit-form', (req, res) => {
var app = express(); res.end(JSON.stringify(req.body))
const bodyParser = require('body-parser') })
app.set("view engine","ejs"); app.listen(3000, function() {
app.use(bodyParser.urlencoded({ extended: false })) console.log("Node server is running..");
app.use(bodyParser.json()) });
app.use(express.json({ extended: false }))
app.get('/formPage', function (req, res) {
res.render('formPage', {
heading: 'Basic Form Example',
})
})
146 Express.js | © Smartcliff | Internal | Version 1.0
Express.js Templating

Form Handling in Express


• The form is rendered as shown below on left on route http://localhost:3000/formPage.

• And on filling and submitting the form, we get a response from the server on route http://localhost:3000/
submit-form as shown below on right.

147 Express.js | © Smartcliff | Internal | Version 1.0


Async / Await

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

148 Express.js | © Smartcliff | Internal | Version 1.0


Asynchronous JS

Async / Await

• Async functions let us write promise-based code as if it were synchronous, but without blocking the

execution thread that allows the code to run asynchronously.

• Roughly, async functions provide better syntax for code that uses Promises.

149 JavaScript | © SmartCliff | Internal | Version 0.1


Asynchronous JS

Async / Await

async Function:

• The async keyword is used to define a function as asynchronous.

• When you declare a function with async, it implicitly returns a Promise.

• Even if you don't explicitly return a Promise within the async function, JavaScript will automatically wrap

the return value (or undefined if nothing is returned) in a resolved Promise.

• Inside an async function, you can use the await keyword

150 JavaScript | © SmartCliff | Internal | Version 0.1


Asynchronous JS

Async / Await

await Operator:

• The await keyword can only be used inside an async function.

• It is placed before a Promise.

• When the JavaScript engine encounters an await keyword, it pauses the execution of the async function

at that point until the Promise resolves (or rejects).

• During this pause, the event loop is not blocked, meaning other asynchronous operations can continue to

execute.Once the Promise resolves, the await expression returns the resolved value of the Promise, and

the async function's execution resumes from where it left off.

151 JavaScript | © SmartCliff | Internal | Version 0.1


Asynchronous JS

Async / Await

• If the Promise rejects, the await expression will throw the rejected value as an error. You'll typically

handle this using try...catch blocks within the async function.

152 JavaScript | © SmartCliff | Internal | Version 0.1


Asynchronous JS

Async / Await

Example:
async function fetchUserData() {

try {

const user = await getUser(1);

console.log('User:', user);

const posts = await getPosts(user.id);

console.log('Posts:', posts);

} catch (error) {

console.error('Error:', error);

}}

fetchUserData();

153 JavaScript | © SmartCliff | Internal | Version 0.1


Asynchronous JS

Async / Await

• Key Benefits of async/await:

• Improved Readability: Makes asynchronous code easier to understand and follow.

• Simplified Error Handling: Uses standard try...catch blocks for error handling, which is more familiar

than .catch() in Promise chains.

• Easier Debugging: Stepping through async/await code in a debugger often feels more natural than

tracing through .then() callbacks.

• Reduces Boilerplate: Less nesting and fewer .then() calls lead to cleaner code.

154 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from
Express
Please download pictures in
suitable size here and insert them
by clicking the symbol above.

155 Express.js | © Smartcliff | Internal | Version 1.0


Fetching JSON from Express

Installation of express module

• 1. You can install this package by using this command.

npm install express

• 2. After installing the express module, you can check your express version in command prompt using

the command.

npm version express

• 3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to
run the following command.

node index.js

156 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Installation of express module

• 4. Install body parser

npm install body-parser

5. Set the start location page in package.json.

"start": "node demo2.js“

6. Start the server

npm start

157 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file

• Front end HTML file (index.html)

<!DOCTYPE html>
<form method="post" action="/">
<html lang="en">
Name: <input type="text"
<head>
name="nametextbox" ><br>
<meta charset="UTF-8">
Age: <input type="text"
<meta name="viewport"
name="agetextbox" >
content="width=device-width, initial-
<input type="submit">
scale=1.0">
<title>Document</title>
</form>
</head>
</body>
<body>
</html>

158 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file <script>


fetch('/loaddata')
.then(response => response.json())
.then(data => {
• Second page HTML file (secondpage.html) var lastdata =
Object.keys(data).length
document.getElementById('datadispl
<!DOCTYPE html>
aypara').textContent = "NAME:"+
<html lang="en">
JSON.stringify(data[lastdata-1].name,
<head>
null, 2) + "/ AGE:"+
<meta charset="UTF-8">
JSON.stringify(data[lastdata-1].age, null,
<meta name="viewport"
2);
content="width=device-width, initial-
})
scale=1.0">
.catch(error => {
<title>Document</title>
document.getElementById('datadispl
</head>
aypara').textContent = 'Error fetching
<body>
data';
<h2>Response from the server is
console.error(error);
displayed here</h2>
});
<p id="datadisplaypara" >
</script>
test
</body>
</p>
</html>

159 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file


function readEntries() {
try {
• Server side file (server.js) const data = fs.readFileSync(myjsonpath,
'utf-8');
var express = require('express'); return JSON.parse(data);
const fs = require('fs'); } catch (err) {
var app = express(); return [];
var PORT = 3000; }
const bodyParser = require('body-parser'); }
const path = require('path'); app.get('/', function (req, res) {
const myjsonpath = path.join(__dirname, res.sendFile(path.join(__dirname,
'data', 'userdetails.json’); 'index.html'));
// Without this middleware });
//app.use(express.json());

app.use(bodyParser.urlencoded({ extended: app.get('/loaddata', function (req, res)


true })); {
const entries = readEntries();
res.json(entries);
});

160 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file

• Server side file (server.js)

const entries = readEntries();


entries.push(data);
app.post('/', function (req, res) {
fs.writeFileSync(myjsonpath,
console.log("Name box value is: " +
JSON.stringify(entries, null, 2));
req.body.nametextbox);
res.sendFile(path.join(__dirname,
console.log("Age text box value is: " +
'secondpage.html'));
req.body.agetextbox);
});
const data = {
name: req.body.nametextbox,
app.listen(PORT, function(err){
age:req.body.agetextbox,
if (err) console.log(err);
};
console.log("Server listening on PORT", PORT);
});

161 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file

• Input

162 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file

• Output

163 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example1: Working with JSON file

• File structure

164 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

• Following example shows CRUD (Create, Read, Update, Delete) operations on a expense details

(transactions).

• User login is validated and redirected to dashboard of the expense details.

• User is allowed to ADD a new expense, VIEW a selected expense, UPDATE a expense and DELETE a

expense details.

165 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Login page- login.html

<body>
<div class="login-container">
<!-- public/login.html -->
<h2>Login</h2>
<!DOCTYPE html>
<form id="loginForm">
<html lang="en">
<input type="text" id="username"
<head>
placeholder="Username" required />
<meta charset="UTF-8" />
<input type="password" id="password"
<meta name="viewport"
placeholder="Password" required />
content="width=device-width, initial-
<button type="submit">Login</button>
scale=1.0"/>
<p id="error" class="error-
<title>Login</title>
message"></p>
<link rel="stylesheet" href="login.css"
</form>
/>
</div>
</head>
<script src="scripts/login.js"></script>
</body>

166 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Login page- login.js

document.getElementById('loginForm').addEv
body: JSON.stringify({ username,
entListener('submit', async (e) => {
password })
e.preventDefault();
});
const username =
if (res.redirected) {
document.getElementById('username').value.
window.location.href = res.url; //
trim();
Redirect to dashboard.html
const password =
} else {
document.getElementById('password').value.
const errorText = await res.text();
trim();
document.getElementById('error').tex
tContent = errorText;
const res = await fetch('/login', {
}
method: 'POST',
});
headers: { 'Content-Type':
'application/json' },

167 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Server.js
// Middleware
app.use(bodyParser.urlencoded({ extended:
true }));
const express = require('express'); app.use(bodyParser.json());
const fs = require('fs'); app.use(express.static(path.join(__dirname
const path = require('path'); , 'public'))); // For HTML/CSS/JS
const bodyParser = require('body-parser');
const app = express(); // Helper functions
const PORT = 3000; function readEntries() {
try {
// File paths const data =
const usersPath = path.join(__dirname, fs.readFileSync(entriesPath, 'utf-8');
'data', 'users.json'); return JSON.parse(data);
const entriesPath = path.join(__dirname, } catch (err) {
'data', 'entries.json'); return [];
}
}

168 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Server.js
fs.readFile(usersPath, 'utf-8', (err, data) =>
{
if (err) return res.status(500).send('Error
function saveEntries(entries) {
reading users');
fs.writeFileSync(entriesPath,
JSON.stringify(entries, null, 2));
const users = JSON.parse(data);
}
const user = users.find(u => u.username ===
// ---------- Routes ---------- //
username && u.password === password);
app.get("/", function(req,res)
{
if (user) {
res.redirect("/login.html");
return res.redirect('/dashboard.html');
});
} else {
res.status(401).send('Incorrect username
// 1. Login Route
or password.'); // Optional: show error in UI
app.post('/login', (req, res) => {
}
const { username, password } = req.body;
});
});

169 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Server.js
// 4. Add new entry
// 2. Get all entries app.post('/entries', (req, res) => {
app.get('/entries', (req, res) => { const newEntry = req.body;
const entries = readEntries(); const entries = readEntries();
res.json(entries);
}); const newId = entries.length > 0 ?
// 3. Get entry by ID Math.max(...entries.map(e => e.id || 0)) + 1 :
app.get('/entries/:id', (req, res) => { 1;
const id = parseInt(req.params.id); const entryWithId = { id: newId, ...newEntry
const entries = readEntries(); };
const entry = entries.find(e => e.id ===
id); entries.push(entryWithId);
if (!entry) return saveEntries(entries);
res.status(404).send('Entry not found');
res.json(entry); res.status(201).json(entryWithId);
}); });

170 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Server.js
// 6. Delete entry by ID
// 5. Update entry by ID
app.delete('/entries/:id', (req, res) => {
app.put('/entries/:id', (req, res) => {
const id = parseInt(req.params.id);
const id = parseInt(req.params.id);
const entries = readEntries();
const updatedData = req.body;
const updatedEntries = entries.filter(e =>
const entries = readEntries();
e.id !== id);
const index = entries.findIndex(e => e.id
=== id);
if (entries.length === updatedEntries.length)
{
if (index === -1) return
return res.status(404).send('Entry not
res.status(404).send('Entry not found');
found');
}
entries[index] = { id, ...updatedData };
saveEntries(entries);
saveEntries(updatedEntries);
res.sendStatus(204);
res.json(entries[index]);
});
});

171 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Server.js

//7. Logout of the page


app.get('/logout', (req, res) => {
req.session.destroy(() => {
res.clearCookie('connect.sid');
res.sendStatus(200); // Works for non-
fetch logout
});
});

// Start server
app.listen(PORT, () => {
console.log(`Server running at
http://localhost:${PORT}`);
});

172 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

• Login page

173 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

• Dashboard page

174 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Actions- Creating / adding a new Actions- Viewing existing


transaction transaction

175 JavaScript | © SmartCliff | Internal | Version 0.1


Fetching JSON from Express

Example2: Handling CRUD operations in JSON file

Actions- Editing a transaction Actions- Deleting a transaction

176 JavaScript | © SmartCliff | Internal | Version 0.1


THANK YOU

You might also like