KEMBAR78
Module 1 - Node JS Rest API (1) (Autosaved) | PDF | Java Script | Computer Programming
0% found this document useful (0 votes)
19 views58 pages

Module 1 - Node JS Rest API (1) (Autosaved)

Cse

Uploaded by

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

Module 1 - Node JS Rest API (1) (Autosaved)

Cse

Uploaded by

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

Naan Mudhalvan Upskilling Platform

A massive industry relevant skill enhancement initiative for the Youth of Tamil Nadu.
IBM Career education program
meticulously designed the EBPL program
and has trained students under the “Naan
mudhalvan” program and by providing
hands-on sessions and industry insights
to the participants
TNSDC IBM FDP AGENDA

Important concepts of Node.js and REST API.

Real-time- Case studies.

Real-time- time Projects

Certification.
WEEK 1 – PROGRAM ORIENTATION

● NodeJS, Express Framework, Installation


● NPM (Node Package Manager)
WEEK 2 & 3 –PRE PROJECT DEVELOPMENT ● Creating a basic Node.js Project

NodeJS and Express ● Handling requests and responses (HTTP & HTTPS
● Calls)

Framework ● Introduction to Express, Advanced Asynchronous


Programming
Fundamentals ● Working with Express
● Introduction to Asynchronous File System
● Introduction to JS ES6, Nodemailer Module
WEEK 9,10- USE CASES AND PROJECT
FINAL ● Session Management, Authorization using JWT
SUBMISSION AND EVALUATION.
JavaScript /NODE JS

● JavaScript is a programming language for client-side web applications that run in a web browser. All
modern web browsers support JavaScript. NodeJS is a cross-platform as well as open-source JavaScript
runtime environment which runs on the V8 JavaScript engine allowing JavaScript to be executed on the
server side.
● Developers build responsive, interactive web applications with HTML, Cascading Style Sheets (CSS),
and JavaScript.
● As an interpreted language, you do not need to compile JavaScript applications before running them. You
can quickly write, test, and debug JavaScript applications with a text editor and a web browser.
JavaScript applications in the web browser.
With client-side JavaScript, developers create rich, interactive web
applications in the web browser.

JavaScript applications in the node server.


With server-side JavaScript, Node applications process and route web service requests from the client.

Compare the following diagram with the one in the previous slide. Most of the steps are identical.

In Step 1, the user selects an option in the user interface, written in HTML and CSS.
Step 2, the option triggers a JavaScript application that implements the business logic on the client side.
Step 3, the JavaScript application makes a web service call over HTTP with a data payload written in JSON.
In the next step, a REST web service intercepts the HTTP request.

The distinction can be seen in the last two steps where:

a. For the client-side JavaScript, the application server is going to process the web service request using a
server-side application, such as Enterprise Java components.
b. For the server-side JavaScript, of invoking an Enterprise Java application, the Node server hosts an
application written in the JavaScript language. This application runs on the server, and not in the client's
web browser.
Key features of NodeJS
● Node is a server-side programming
framework that uses JavaScript as its
programming language
● Node is built with a heavy emphasis on
concurrent programming with a lightweight
language
● Node is suited for developers that want to
build scalable, concurrent server applications
quickly with a minimal set of tools
● NodeJS also comes with built-in support for
package management using the NPM (Node
Package Manager) tool that comes by default
with every Node.js installation.
● NodeJS runs on Google’s open source
JavaScript engine called V8.
● It reduces the need for separate languages or
code bases between front-end and backend
applications.
● It uses JavaScript’s asynchronous
programming style via the use of event loops
with callbacks to make applications fast,
efficient, and non-blocking.
NodeJS Architecture

Node.js uses the concepts of Asynchronous


model and non-blocking I/O. It makes use of
the “Single Threaded Event Loop” architecture
in order to handle multiple concurrent clients.
Node.JS Processing Model makes use of
JavaScript event-based model along with the
JavaScript Callback mechanism.

Node.js makes use of Google’s open source V8


engine which is a library of C++ code which in
turn compiles our JavaScript code to Machine
Level Language for it to be understood and
executed
NodeJS Architecture

● Requests: Incoming requests depend on the task that is being performed in a web
application.
● Node.js server: Is a server-side platform which receives, processes the requests to
return response to the corresponding user.
● Event Queue: It stores incoming requests and sends them one-by-one to the
Event Loop.
● Thread pool: Contains all threads available for carrying out tasks to fulfill
requests.
● Event Loop: Event Loop continually receives, and processes requests and then
returns response to corresponding clients.
Express
● Framework
Express is a minimal and flexible Node.js
web application framework that provides a
robust set of features for web and mobile
applications.
● It is a light-weight, fast, flexible and simple
web development framework which provides
several great features such as an intuitive
view system, robust routing, an executable
for generating applications and much more.
Express is one of most popular choice for
developing Node JS applications. We will be
using express framework in code samples
throughout this document.
Node.js installation
1. Navigate to https://nodejs.org/en/download , choose the appropriate installer, download and
install.
2.On Windows download the Windows installer (.msi ) file.

3. Double-Click on the downloaded installer and click on Next


4. Accept the End-User License Agreement and Click on Next
5. Choose install location as C:\nodejs and Click on Next

6. Accept defaults and Click on Next


7. One may skip installation of optional dependencies such as Chocolatey.
And click on “Install”

Administrator permissions are required for the installer.


8. Click Finish

NodeJs is now installed in your machine.


You can run “node -v” in command prompt.
Install Express JS

Before staring Express JS Development, first and fore most step we need to do is use “npm install”
command to install Express JS module.

1.Open command prompt and change directory to C:\nodejs install folder


2. Run command npm install -g express Here “express” means
Express JS Module and “-g” means install Express JS Module
globally.

3. To verify if installed successfully, we can find a new folder at: C:\Users\[Windows_UserName]\


AppData\Roaming\npm\node_modules\express Now install the express application generator tool,
to quickly create an application skeleton. The express-generator package installs the express
command-line tool.

4. Run command npm install express-generator -g


5. Run command express <new project name>

6. Change directory to test1app cd test1app


7. Then, type npm install to install dependencies.

8. On Windows, use this command: > set DEBUG=myapp:* & npm start
9. On MacOS or Linux, run the app with this command: $ DEBUG=myapp:* npm start
10. Then load http://localhost:3000/ in your browser to access the app.
11. Folder structure generated:
Setting up a Node.js environment
1. Go to https://www.eclipse.org/downloads/ and download eclipse of your
choice. Recommended is ‘Eclipse IDE for Java EE Developers’.
2. Start eclipse.
3. Go to Help > Eclipse Marketplace
4. Type Node eclipse in search field and press Go.
5. Select Nodeclipse 1.0.2 ( or later version ) and press Install
6. Also download Nodeclipse/Enide Grade for Eclipse 0.17 and press Install

7. Restart eclipse after both plugins are installed.


Introduction to NPM(Node Package Manager)

● npm is the package manager for Node.js and is currently the largest software registry
containing over 2.1 Million packages. The npm registry is the center of JavaScript code
sharing; to be used be Open-Source Developers.
● NPM is a tool that comes with Node.js. It is used to install and manage third-party
packages and modules that help us build applications faster, such as Express.js,
Nodemailer, etc.
● Primarily built to download & manage the dependencies of Node.js packages, it has
now also evolved to a tool which can be used in frontend JavaScript.
● It is free to use and is coupled with the installation of Node.js and all the npm public
software packages can be downloaded and used without any registration or login
required.
Creating a basic Node.js Project
1. Open Eclipse and change to Node perspective Window -> Perspective
-> Open Perspective -> Other -> Node

Exploratory Data
Analysis (EDA):
• Summarizing and visualizing
data.
2. Select Window -> Preferences -> Nodeclipse
3. Update Node.js path and Express path according to your install location.
Node.js path = C:\NodeJS\node.exe Express path = C:\Users\<yourusername>\AppData\
Roaming\npm\node_modules\express-generator\bin\express-cli.js
4. Click on Apply and then OK
Click File -> New -> Node.js Express Project as shown below
6. Select the options and type project name. Note that 'ejs' has been selected as Template
Engine.

7. A default NodeJS Express Project is created with the following structure.


8. Right click on package.json and click on Run As -> npm Install
9. Update app.js to match:

var http = require('http');


var express = require('express');
http.createServer(function handler(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Express app started from Eclipse\n'); }).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
10. Right click on app.js and click on Run As -> Node.js Application
11. Open link http://127.0.0.1:1337/ and you’ll see you ‘’Express app started
from Eclipse’ webpage.
Handling requests and responses (HTTP & HTTPS Calls)

● Performing actions on the UI of the application leads to the client sending a


request messages to the server.

● This request is met with a response that is generated and returned to the client as
a reply to the request message.

● A request usually consists of a request line that has the request method and
requested URL. <request-method> <request-target>["?"<query>] HTTP/1.1

Request methods can be of the following types:

1. GET - requests that are aimed at retrieving data (representation of state) from the target.
2. POST – requests for which the target must process the representation defined in the request according to the rules setup in the
target.
3. PUT - requests the target to create or update its state with the representation defined in the request.
4. DELETE – requests the target to delete its state for the requested representation.
5. HEAD – requests which retrieve the representation metadata in the response header, not the entire representation.

There are other Request methods worthy of mentions such as:


1. CONNECT - requests to secure connections through HTTP proxies with Transport Layer Security
2. OPTIONS – requests for the HTTP methods supported by the target.
3. TRACE – this method helps us in debugging with message loop-backs along the path defined in the request.
4. PATCH – requests for making partial changes to existing resources.
Categorizations of request methods:

1.Safe Methods: Methods which do not intend any change or


effect to the target server are called Safe Methods. The
methods GET, HEAD, OPTIONS and TRACE are safe
methods. Note:- POST, PUT, DELETE, CONNECT, and
PATCH are not safe methods as the do intend some changes
to the target.

2. Idempotent Methods: Request methods are Idempotent


Methods if multiple requests of that method have the same
effect as a singular execution. PUT and DELETE along with
the Safe Methods are Idempotent Methods. POST,
CONNECT, and PATCH are not necessarily idempotent.

3. Cacheable Methods: Request methods are considered


cacheable if responses to these requests may be stored to
be reused. GET, HEAD and POST are cacheable methods.
PUT, DELETE, CONNECT, OPTIONS, TRACE, and PATCH
are not cacheable.
Introduction to Express

Express.js framework works on top of the web server functionalities of Node.js


It is open source, managed by the NodeJS foundation.
It is a part of the MEAN stack which is used to build web applications.
MEAN is a JavaScript Full Stack solution comprising of:

1. Mongo DB - Database
2. ExpressJS – Web Framework
3. AngularJS – Frontend Framework
4. NodeJS – Application Server
Features of Express.js:
1. Easy organization of functionalities with middleware as well as routing.
2. Adding utilities to HTTP objects
3. Renders dynamic HTTP objects
4. Addition of templating engines
5. Easier usage of static files from within the application

Express.js helps in the development of robust APIs adhering to REST architecture.

It also helps creating real-time applications and Single Page Applications which effortlessly update content on the client-side dyncamically.Express
works between the request and the response as it serves as a Middleware framwork. It helps handing client requests by intercepting and
manipulating client requests and server responses. Middleware is a set of functions which Express.js utilizes in the routing layer of the application.

Types of Express functions are:


1. Express Application Functions such as app.disabled(), app.all(), app.delete()
2. Express express functions such as express.Router(), express.static()
3. Express request and response functions such as req.app Property, req.acceptsEncodings() res.download() function
4. Express Routing functions such as router.all() and router.METHOD()
Asynchronous
Programming
● Asynchronous Programming is a paradigm used in Node.js development, allowing us to perform concurrent tasks
without blocking other operations.
● Callbacks are widely used to handle these operations asynchronously. These can sometimes lead to complex
nested code raising the challenge called Callback Hell.
● A callback is a function that's passed as a parameter to another method/function and is executed when the event
happens. It can be thought of as an event handler for a performed action. Such as on button click on UI.

Blocking Example (Sync):

const fs = require('fs');
const data = fs.readFileSync('file.txt'); // Blocks here
console.log(data.toString());

Non-blocking Example (Async):


fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
Working with Express
1. Routing in Express

Handles different HTTP methods (GET, POST, PUT, DELETE)


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

app.post('/users', (req, res) => {...});

2. Middleware

Functions that execute before route handlers.


app.use(express.json()); // built-in middleware for parsing JSON

3. Modular Routing

Use express.Router() for clean code organization:


const router = express.Router();

router.get('/posts', (req, res) => {...});

app.use('/api', router);
Introduction to Asynchronous File System

The File System module (fs) provides an API to communicate and perform operations on the file
system. It allows operations like reading, writing, updating files and deleting files & directories.It
allows the functionalities of file I/O with the use of wrappers modeled on or around standard
POSIX functions.POSIX - Portable Operating System Interface.These file operations can be
synchronous or asynchronous depending on the requirements of your application.
To define this module in our Node.js applications we make use of the line:
const fs = require('fs');

1. fs.readFile() – Read a File


Definition:
Reads the entire contents of a file asynchronously. It doesn't block the execution thread.

Syntax:

fs.readFile(path, options, callback);


Introduction to Asynchronous File System
2. fs.writeFile() – Write to a File
Definition:
Creates a new file or overwrites an existing file with the provided content, asynchronously.

Syntax:

fs.writeFile(path, data, options, callback);

3. fs.open() – Open a File


Definition:
Opens a file for reading, writing, or both. Returns a file descriptor (a low-level reference to the file).

Syntax:

fs.open(path, flags, mode, callback);

4. fs.unlink() – Delete a File


Definition:
Deletes a file asynchronously from the file system.

Syntax:

js
CopyEdit
Introduction to Asynchronous File System

5. Writing a File Asynchronously – Full Breakdown


Writing to a file asynchronously we will create a new folder and for this course’s purpose we will
name is ‘File System Operations’.
In this folder we will create a file ‘main.js’ in which we will write data to a new file.

Our aim is to write a program that creates a new file as well as writes to it asynchronously.
New folder containing only our js file:
main.js:

const fs = require('fs'); //Defining the filesystem module to be used further


const asyncWriteExample = 'Data is written to this file in asynchronous mode using callbacks';
//Data we want to write to the file.
fs.writeFile('./testasyncWriteExample.txt', asyncWriteExample, errObj => {
if (errObj) {
console.error(errObj); //Error Handling
} else {
console.log("File write operation was successful.");
}
});

We run this code using command prompt

Now we see a new file has been created in our folder and its
contents:
File 'testasyncWriteExample.txt'

Other I/O Operations

1. fs.appendFile() - Used to append data to a file.


2. fs.createReadStream() or fs.createWriteStream() – For reading from or writing to files
using streams.
3. fs.watch() – To watch for changes in a file or directory using eventTypes.
4. fs.copyFile() – To copy a file from one location to another.
5. fs.rename() – To move or rename a file.
6. fs.readdir(), fs.mkdir() or fs.mkdirSync() & fs.rmdir() or fs.rmdirSync() – To get lists
of files in a director, create or delete a directory respectively.
7. fs.stat(), fs.fstat(), or fs.lstat() - To retrieve file/directory metadata, like size, modified
times, and permissions.
8. It is important to note that a lot of the fs methods are coupled with promise-based
counterparts from the fs/promises module, which allow to use async/await. Example
fsPromises.readFile()
Introduction to JS ES6
ES6 (ECMAScript 6), officially known as ECMAScript 2015, is a major update to
JavaScript that introduced many powerful and modern features, making code cleaner,
easier to manage, and more maintainable.
Some features that ES6 brought to JavaScript are:
• Modules – ES6 brought about support for modules, allowing developers to import & export functions/methods, and objects from
one module to another.

1. Export: This allows to export functions, objects, or variables from required modules.
2. Import: This allows to import the exported entities from the required modules.
3.Promises – ES6 gave us a way to handle asynchronous operations more efficiently than callbacks.
4.Classes - Classes are used to create objects with the help of a constructor
5.Arrow Functions - It allowed a shorter syntax for writing function definitions as you no longer required the keywords ‘function’,
’return’ or the curly braces. const multiply = (a, b) => a * b;
6.Template Literals – Made it easier to create strings, especially when embedding variables or expressions is required. Backticks
(') are used for
this.
const a = "JohnDoe";
const b = 'Student ${a}';

7.Destructuring Assignment - syntax used to unpack values from arrays or required properties from the object into distinct
variables for usage.
const array = [11, 22, 33]; //We define an array with some default values
const [x, y] = array; //x takes value 11 and y takes the value 22.

8.Default Parameters – Allows for parameters to have set default values.


Nodemailer Module
● The Nodemailer module is a Node.js Module that can be made use of for
sending emails as it makes it easy to use the various transport mechanisms
required AI
by the application.
● It is a module that allows sending emails from your server, be it
communicating with users or notifications of any application related update.
Nodemailer – Sending Emails in Node.js
🔹 Step 1: Install Nodemailer
npm install nodemailer
🔹 Step 2: Import Module
const nodemailer = require('nodemailer');
🔹 Step 3: Create Transporter
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_app_password'
}
});
🔹 Step 4: Define Mail Options
const mailOptions = {
from: 'your_email@gmail.com',
to: 'recipient@example.com',
subject: 'Test Email',
text: 'Hello from Nodemailer!'
};
🔹 Step 5: Send Email
transporter.sendMail(mailOptions, (error, info) => {
if (error) return console.log(error);
console.log('Email sent:', info.response);
});
Session Management
● Manages user state across multiple requests.

● Stores session ID in cookies, URL, or browser storage.


● Session data (user login, cart, etc.) = Session State.
● Sessions can timeout for security.
● Useful for tracking users and handling multiple requests.

Node.js Session Libraries


1. express-session – Simple server-side session management.

2. connect-redis – Stores sessions in Redis (for scalability).

3. cookie-session – Stores session data in cookies.


● Installation
npm install express express-session
● File session Management.js:
const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
secret: '7332',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));

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


req.session.visitCount = (req.session.visitCount || 0) + 1;
res.send(`Visits: ${req.session.visitCount}`);
});

app.listen(3005, () => {
console.log('Running on http://localhost:3005');
});
Running the application (Session 1):

URL: http://localhost:3005/
Authorization using JWT

JWT stands for ‘JSON Web Tokens’ which is a method to perform authentications and
authorizations in applications. It is a compact representation of claims to be transferred.

There are three parts to a JWT which are all separated by dots (.):
1. Header: Metadata of the token, specifying signing algorithms such as HMAC or
RSA.
2. Payload: Holds the claims about the user and additional data such as User ID, roles
and auth expiration times.
3. Signature: Ensures that the token has not been tampered with. The header and
payload are put together and digitally signed using a secret key.
Authorization using JWT

Structure of JWT: <header>.<payload>.<signature> where header, payload and


signature are alphanumeric strings.
Process of JWT Authorization:
1. User Login: User sends authorization credentials to the server and receives a JWT
from the server if the credentials are accepted.
2. Token Storage: Client application stores the JWT using local storage or cookies.
3. Requesting Protected Resources: While requesting for protected resources, the
client includes the JWT in the auth header: Authorization: Bearer <token>
4. Token Verification: After receiving the request, the server verifies the Signature
using the secret key.
5. Access Control: On successful validation. The request is processed and the server
returns to the desired resource. If validation fails, it responds with error codes such as
401 – Unauthorized.
Authorization using JWT

Structure of JWT: <header>.<payload>.<signature> where header, payload and


signature are alphanumeric strings.
Process of JWT Authorization:
1. User Login: User sends authorization credentials to the server and receives a JWT
from the server if the credentials are accepted.
2. Token Storage: Client application stores the JWT using local storage or cookies.
3. Requesting Protected Resources: While requesting for protected resources, the
client includes the JWT in the auth header: Authorization: Bearer <token>
4. Token Verification: After receiving the request, the server verifies the Signature
using the secret key.
5. Access Control: On successful validation. The request is processed and the server
returns to the desired resource. If validation fails, it responds with error codes such as
401 – Unauthorized.
Develop a codebase with JWT

We will implement JWT authorization in Node.js using jsonwebtoken library.


To begin we have to install the dependencies of jsonwebtoken.

npm install express jsonwebtoken body-parser


Step 1: Setup Environment

● Create a file: jwtAuthorization.js

● Run in terminal:
npm install express jsonwebtoken body-parser

📦 Step 2: Import Required Packages

const express = require('express');


const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

⚙️Step 3: Initialize App


const app = express();
const PORT = process.env.PORT || 3007;
const SECRET_KEY = 'jwt.example.chapter17';

🧠 Step 4: Use Middleware

● Enables JSON parsing in requests:


app.use(bodyParser.json());
👤 Step 5: Mock User Data

const users = [{ id: 1, username: 'testUser1', password: 'password' }];

🔑 Step 6: Create Login Route

● Verifies credentials

● Signs a JWT if correct


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

const { username, password } = req.body;


const user = users.find(u => u.username === username && u.password === password);

if (user) {
const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '1h' });
return res.json({ token });
}
res.status(401).send('Invalid credentials');
});

Test this POST route using Postman

🧪 Step 7: Create Middleware to Verify JWT


const authenticateJWT = (req, res, next) => {
const token = req.headers['authorization']?.split(' ')[1];
if (token) {
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403); // Forbidden
req.user = user;
next();
});
} else {
res.sendStatus(401); // Unauthorized
}
🔐 Step 8: Create a Protected Route

● Only accessible with valid token


app.get('/protected', authenticateJWT, (req, res) => {
res.send('This is a protected route. Your authorization was successful');
});

🚀 Step 9: Start the Server

app.listen(PORT, () => {
console.log(`Auth server started on http://localhost:${PORT}`);
});

You might also like