Introduction to Node JS | Cheat Sheet • Node CLI
Concepts in Focus 3.1 Node REPL (Read-Eval-Print-Loop)
• MERN Stack Type node in the terminal and press Enter
• Node JS root@123# node
• Running JavaScript Using Node JS Welcome to [Link] v12.18.3.
o Node REPL (Read-Eval-Print-Loop) Type ".help" for more information.
o Node CLI > const a = 1
• Module undefined
o Common JS Module Exports > const b = 2
o Modern JS Module Exports undefined
1. MERN Stack > a+b
MERN stands for MongoDB, Express JS, React JS and Node JS. 3
It is a JavaScript Stack that is used for easier & faster deployment of >
full-stack web applications.
Type .exit and press Enter to exit from the Node REPL.
2. Node JS
root@123# node
Node JS is a JavaScript environment that executes JavaScript code
Welcome to [Link] v12.18.3.
outside a web browser.
Type ".help" for more information.
Why Node JS?
> const a = 1
• Cross-Platform (Windows, Linux, Mac OS X, etc.)
undefined
• Huge number of third-party packages
> const b = 2
• Open Source
undefined
• Massive Community
> a+b
3. Running JavaScript Using Node JS
3
We can run JavaScript using Node JS in 2 ways.
> .exit
• Node REPL (Similar to browser console)
root@123:/home/workspace#
Collapse o Named Exports
3.2 Node CLI 4.1 Common JS Module Exports
We can write JavaScript to a file and can run using Node CLI. 4.1.1 Default Exports
//[Link] Exporting Module
const greetings = (name) => { The [Link] is a special object included in every JavaScript
file in the Node JS application by default.
[Link](`Hello ${name}`);
//[Link]
};
const add = (a, b) => {
greetings("Raju");
return a + b;
greetings("Abhi");
};
JAVASCRIPT
root@123# node [Link] [Link] = add;
Hello Raju JAVASCRIPT
Hello Abhi Importing Module
To import a module which is the local file, use the require() function
Note
with the relative path of the module (file name).
Save the file whenever the code changes.
//[Link]
4. Module
const add = require("./calculator");
In Node JS, each JavaScript file is treated as a separate module. These
are known as the Common JS/Node JS Modules. [Link](add(6, 3));
JAVASCRIPT
To access one module from another module, we have Module
Exports. Output
• Common JS Module Exports root@123# node [Link]
o Default Exports 9
o Named Exports 4.1.2 Named Exports
• Modern JS Module Exports We can have multiple named exports per module.
o Default Exports Exporting Module
//[Link] 4.2.1 Default Exports
const add = (a, b) => { Exporting Module
return a + b; //[Link]
}; const add = (a, b) => {
const sub = (a, b) => { return a + b;
return a - b; };
}; export default add;
[Link] = add; JAVASCRIPT
[Link] = sub; Importing Module
JAVASCRIPT //[Link]
Collapse import add from "./[Link]";
Importing Module [Link](add(6, 3));
//[Link] JAVASCRIPT
const { add, sub } = require("./calculator"); Output
[Link](add(6, 3)); root@123# node [Link]
[Link](sub(6, 3)); 9
JAVASCRIPT 4.2.2 Named Exports
Output Exporting Module
root@123# node [Link] //[Link]
9 export const add = (a, b) => {
3 return a + b;
4.2 Modern JS Module Exports };
Modern JS Modules are known as ES6 Modules. export const sub = (a, b) => {
The export and import keywords are introduced for exporting and return a - b;
importing one or more members in a module.
};
JAVASCRIPT o Exporting a class after defining
Importing Module • Named Exports
//[Link] o Exporting multiple variables while defining
import { add, sub } from "./[Link]"; o Exporting multiple variables after defining
[Link](add(6, 3)); o Exporting multiple values and expressions
[Link](sub(6, 3)); o Exporting multiple functions while defining
JAVASCRIPT o Exporting multiple functions after defining
Output o Exporting multiple classes while defining
root@123# node [Link] o Exporting multiple classes after defining
9 Let's see different scenarios that we may come across while exporting.
3 1. Default Exports
Note With Default Exports, we can import modules with any name.
• We need to specify .mjs extension while importing ES6 1.1 Exporting a variable while defining
Modules.
We cannot export boolean, number, string, null, undefined, objects,
• We may or may not need to specify .js while importing and arrays while defining.
Common JS Modules. Example:
Common JS Module Exports | Reading Material //[Link]
Concepts in Focus [Link] = let value = 5;
• Default Exports
JAVASCRIPT
o Exporting a variable while defining
//[Link]
o Exporting a variable after defining
const num = require("./[Link]");
o Exporting a value or an expression
JAVASCRIPT
o Exporting a function while defining
Output
o Exporting a function after defining root@123# node [Link]
o Exporting a class while defining /[Link]
[Link] = let value = 5; JAVASCRIPT
^ //[Link]
SyntaxError: Unexpected identifier const result = require("./[Link]");
at wrapSafe (internal/modules/cjs/[Link]:16) [Link](result);
... JAVASCRIPT
1.2 Exporting a variable after defining Output
We can export boolean, number, string, null, undefined, objects, and root@123# node [Link]
arrays after defining.
15
Example:
1.4 Exporting a function while defining
//[Link]
We can export a function while defining.
let value = 5; Example:
[Link] = value; //[Link]
JAVASCRIPT [Link] = function (num1, num2) {
//[Link]
return num1 + num2;
const value = require("./[Link]");
};
[Link](value);
JAVASCRIPT
JAVASCRIPT
//[Link]
Output
const sum = require("./[Link]");
root@123# node [Link] [Link](sum(2, 6));
5 JAVASCRIPT
1.3 Exporting a value or an expression Output
We can export a value or an expression directly.
root@123# node [Link]
Example:
8
//[Link]
1.5 Exporting a function after defining
[Link] = 5 * 3;
We can export a function after defining.
Example: //[Link]
//[Link] const StudentDetails = require("./[Link]");
function sum(num1, num2) { const studentDetails = new StudentDetails("Ram", 15);
return num1 + num2; [Link](studentDetails);
} [Link]([Link]);
[Link] = sum; JAVASCRIPT
JAVASCRIPT Output
//[Link] root@123# node [Link]
const sum = require("./[Link]"); StudentDetails { name: 'Ram', age: 15 }
[Link](sum(2, 6)); Ram
JAVASCRIPT 1.7 Exporting a class after defining
Output We can export a class after defining.
root@123# node [Link] Example:
8 //[Link]
1.6 Exporting a class while defining class StudentDetails {
We can export a class while defining. constructor(name, age) {
Example: [Link] = name;
//[Link] [Link] = age;
[Link] = class StudentDetails { }
constructor(name, age) { }
[Link] = name; [Link] = StudentDetails;
[Link] = age; JAVASCRIPT
} //[Link]
}; const StudentDetails = require("./[Link]");
JAVASCRIPT const studentDetails = new StudentDetails("Ram", 15);
[Link](studentDetails); SyntaxError: Unexpected identifier
[Link]([Link]); at wrapSafe (internal/modules/cjs/[Link]:16)
JAVASCRIPT 2.2 Exporting multiple variables after defining
Output We can export multiple variables after defining.
root@123# node [Link] Example:
StudentDetails { name: 'Ram', age: 15 } //[Link]
Ram let value = 5;
2. Named Exports [Link] = value;
2.1 Exporting multiple variables while defining let studentName = "Rahul";
We cannot export boolean, number, string, null, undefined, objects, [Link] = studentName;
and arrays while defining. JAVASCRIPT
Example: //[Link]
//[Link] const { value, studentName } = require("./sample");
[Link] = let value = 5;
[Link](value);
[Link] = let studentName = "Rahul";
[Link](studentName);
JAVASCRIPT
JAVASCRIPT
//[Link]
Output
const { value, studentName } = require("./sample");
root@123# node [Link]
[Link](value); 5
[Link](studentName); Rahul
JAVASCRIPT 2.3 Exporting multiple values and expressions
Output
We can export multiple values and expressions.
root@123# node [Link]
Example:
[Link] = let value = 5;
//[Link]
^^^^^
let value = 2;
[Link] = 2 + 3; JAVASCRIPT
[Link] = 3 - value; Output
JAVASCRIPT root@123# node [Link]
//[Link] 8
const { sum, sub } = require("./sample"); 5
[Link](sum); 2.5 Exporting multiple functions after defining
[Link](sub); We can export multiple functions after defining.
JAVASCRIPT Example:
Output //[Link]
root@123# node [Link] function sum(num1, num2) {
2.4 Exporting multiple functions while defining return num1 + num2;
We can export multiple functions while defining. }
Example: [Link] = sum;
//[Link] function sub(num1, num2) {
[Link] = function (num1, num2) { return num1 - num2;
return num1 + num2; }
}; [Link] = sub;
[Link] = function sub(num1, num2) { JAVASCRIPT
return num1 - num2; //[Link]
}; const { sum, sub } = require("./sample");
JAVASCRIPT [Link](sum(2, 6));
//[Link] [Link](sub(8, 3));
const { sum, sub } = require("./sample"); JAVASCRIPT
[Link](sum(2, 6)); Output
[Link](sub(8, 3)); root@123# node [Link]
8 const newCarDetails = new carDetails("Alto", "60kmph");
5 [Link](newCarDetails);
2.6 Exporting multiple classes while defining [Link]([Link]);
We can export multiple classes while defining. JAVASCRIPT
Example: Collapse
//[Link] Output
[Link] = class StudentDetails { root@123# node [Link]
constructor(name, age) { StudentDetails { name: 'Ram', age: 15 }
[Link] = name; Ram
[Link] = age; CarDetails { name: 'Alto', speed: '60kmph' }
} Alto
}; 2.7 Exporting multiple classes after defining
[Link] = class CarDetails { We can export multiple classes after defining.
constructor(name, age) { Example:
[Link] = name; //[Link]
[Link] = age; class StudentDetails {
} constructor(name, age) {
}; [Link] = name;
JAVASCRIPT [Link] = age;
Collapse }
//[Link] }
const { studentDetails, carDetails } = require("./[Link]"); [Link] = StudentDetails;
const newStudentDetails = new studentDetails("Ram", 15); class CarDetails {
[Link](newStudentDetails); constructor(name, age) {
[Link]([Link]); [Link] = name;
[Link] = age; ES6 Module Exports | Reading Material
} Concepts in Focus
} • Default Exports
[Link] = CarDetails; o Exporting a variable while defining
JAVASCRIPT o Exporting a variable after defining
Collapse o Exporting a value or an expression
//[Link] o Exporting a function while defining
const { studentDetails, carDetails } = require("./[Link]"); o Exporting a function after defining
const newStudentDetails = new studentDetails("Ram", 15); o Exporting a class while defining
[Link](newStudentDetails); o Exporting a class after defining
[Link]([Link]); • Named Exports
const newCarDetails = new carDetails("Alto", "60kmph"); o Exporting multiple variables while defining
[Link](newCarDetails); o Exporting multiple variables after defining
[Link]([Link]); o Exporting multiple functions while defining
o Exporting multiple functions after defining
JAVASCRIPT o Exporting multiple classes while defining
Expand o Exporting multiple classes after defining
Output Let's see different scenarios that we may come across while exporting.
root@123# node [Link] 1. Default Exports
StudentDetails { name: 'Ram', age: 15 } With Default Exports, we can import modules with any name.
Ram 1.1 Exporting a variable while defining
CarDetails { name: 'Alto', speed: '60kmph' } We cannot export boolean, number, string, null, undefined, objects,
and arrays while defining.
Alto
Example:
//[Link]
export default let value = 5; JAVASCRIPT
JAVASCRIPT Output
//[Link] root@123# node [Link]
import value from "./[Link]"; (node:32665) ExperimentalWarning: The ESM module loader is
[Link](value); experimental.
5
JAVASCRIPT
1.3 Exporting a value or an expression
Output
We can export a value or an expression directly.
root@123# node [Link]
Example:
(node:31964) ExperimentalWarning: The ESM module loader is
experimental. //[Link]
[Link] export default 5 * 3;
export default let value = 5; JAVASCRIPT
^^^ //[Link]
SyntaxError: Unexpected strict mode reserved word import result from "./[Link]";
1.2 Exporting a variable after defining [Link](result);
We can export boolean, number, string, null, undefined, objects, and JAVASCRIPT
arrays after defining. Output
Example: root@123# node [Link]
//[Link]
(node:4071) ExperimentalWarning: The ESM module loader is
let a = 5; experimental.
export default a; 15
JAVASCRIPT 1.4 Exporting a function while defining
//[Link] We can export a function while defining.
import a from "./[Link]"; Example:
[Link](a); //[Link]
export default function (num1, num2) { JAVASCRIPT
return num1 + num2; Output
} root@123# node [Link]
JAVASCRIPT (node:4462) ExperimentalWarning: The ESM module loader is
//[Link] experimental.
8
import sum from "./[Link]";
1.6 Exporting a class while defining
[Link](sum(2, 6));
We can export a class while defining.
JAVASCRIPT
Example:
Output
//[Link]
root@123# node [Link]
(node:4278) ExperimentalWarning: The ESM module loader is export default class StudentDetails {
experimental. constructor(name, age) {
8 [Link] = name;
1.5 Exporting a function after defining [Link] = age;
We can export a function after defining. }
Example: }
//[Link] JAVASCRIPT
function sum(num1, num2) { //[Link]
return num1 + num2; import StudentDetails from "./[Link]";
} const newStudentDetails = new StudentDetails("Ram", 15);
export default sum; [Link](newStudentDetails);
JAVASCRIPT [Link]([Link]);
//[Link] JAVASCRIPT
import sum from "./[Link]"; Output
[Link](sum(2, 6)); root@123# node [Link]
(node:1035) ExperimentalWarning: The ESM module loader is (node:1575) ExperimentalWarning: The ESM module loader is
experimental. experimental.
StudentDetails {name: "Ram", age: 15} StudentDetails {name: "Ram", age: 15}
Ram Ram
1.7 Exporting a class after defining 2. Named Exports
We can export a class after defining. 2.1 Exporting multiple variables while defining
Example: We can export boolean, number, string, null, undefined, objects, and
//[Link] arrays while defining.
class StudentDetails { Example:
constructor(name, age) { //[Link]
export let value = 5;
[Link] = name;
export let studentName = "Rahul";
[Link] = age;
JAVASCRIPT
}
//[Link]
}
import { value, studentName } from "./[Link]";
export default StudentDetails;
JAVASCRIPT [Link](value);
//[Link] [Link](studentName);
import StudentDetails from "./[Link]"; JAVASCRIPT
Output
const newStudentDetails = new StudentDetails("Ram", 15);
root@123# node [Link]
[Link](newStudentDetails);
(node:1770) ExperimentalWarning: The ESM module loader is
[Link]([Link]);
experimental.
JAVASCRIPT
5
Output
Rahul
root@123# node [Link]
2.2 Exporting multiple variables after defining
We can export multiple variables after defining in an Object format.
Example: return num1 - num2;
//[Link] }
let value = 5; JAVASCRIPT
const studentName = "Rahul"; //[Link]
export { value, studentName }; import { sum, sub } from "./[Link]";
JAVASCRIPT [Link](sum(4, 2));
//[Link] [Link](sub(4, 2));
import { value, studentName } from "./[Link]"; JAVASCRIPT
[Link](value); Output
[Link](studentName); root@123# node [Link]
JAVASCRIPT (node:2954) ExperimentalWarning: The ESM module loader is
Output experimental.
root@123# node [Link] 6
2
(node:2437) ExperimentalWarning: The ESM module loader is
experimental. 2.4 Exporting multiple functions after defining
5 We can export multiple functions after defining.
Rahul Example:
2.3 Exporting multiple functions while defining //[Link]
We can export multiple functions while defining. function sum(num1, num2) {
Example: return num1 + num2;
//[Link] }
export function sum(num1, num2) { function sub(num1, num2) {
return num1 + num2; return num1 - num2;
} }
export function sub(num1, num2) { export { sum, sub };
JAVASCRIPT [Link] = name;
Collapse [Link] = speed;
//[Link] }
import { sum, sub } from "./[Link]"; }
[Link](sum(4, 2)); JAVASCRIPT
[Link](sub(4, 2)); Collapse
JAVASCRIPT //[Link]
Output import { StudentDetails, CarDetails } from "./[Link]";
root@123# node [Link] const newStudentDetails = new StudentDetails("Ram", 15);
(node:3276) ExperimentalWarning: The ESM module loader is [Link](newStudentDetails);
experimental. [Link]([Link]);
6 const newCarDetails = new CarDetails("Alto", "60kmph");
2 [Link](newCarDetails);
2.5 Exporting multiple classes while defining
[Link]([Link]);
We can export multiple classes while defining.
JAVASCRIPT
Example:
Collapse
//[Link]
Output
export class StudentDetails {
root@123# node [Link]
constructor(name, age) { (node:3517) ExperimentalWarning: The ESM module loader is
[Link] = name; experimental.
[Link] = age; StudentDetails { name: 'Ram', age: 15 }
} Ram
} CarDetails { name: 'Alto', speed: '60kmph' }
export class CarDetails { Alto
constructor(name, speed) { 2.6 Exporting multiple classes after defining
We can export multiple classes after defining. [Link]([Link]);
Example: JAVASCRIPT
//[Link] Collapse
class StudentDetails { Output
constructor(name, age) { root@123# node [Link]
[Link] = name; (node:3841) ExperimentalWarning: The ESM module loader is
experimental.
[Link] = age;
StudentDetails {name: "Ram", age: 15}
}
Ram
}
CarDetails {name: "Alto", speed: "60kmph"}
class CarDetails {
constructor(name, speed) { Alto
[Link] = name;
[Link] = speed; Introduction to Node JS | Part 2 | Cheat Sheet
Concepts in Focus
}
• Core Modules
}
o Path
export { StudentDetails, CarDetails };
• Package
JAVASCRIPT
o Node Package Manager (NPM)
Collapse
//[Link] • Steps to create a Node JS Project
import { StudentDetails, CarDetails } from "./[Link]"; • Third-Party Packages
const newStudentDetails = new StudentDetails("Ram", 15); o date-fns
1. Core Modules
[Link](newStudentDetails);
The Core Modules are inbuilt in Node JS.
[Link]([Link]);
Some of the most commonly used are:
const newCarDetails = new CarDetails("Alto", "60kmph");
[Link](newCarDetails);
NPM is the package manager for the Node JS packages with more
Module Description
than one million packages.
path Handles file paths It provides a command line tool that allows you to publish, discover,
fs Handles the file system install, and develop node programs.
2.1.1 CLI
url Parses the URL strings
NPM CLI sets up the Node JS Project to organize various modules
1.1 Path
and work with third-party packages.
The path module provides utilities for working with file and directory
paths. It can be accessed using: Command Description
const path = require("path"); Initializes a project and creates a
npm init -y
JAVASCRIPT [Link] file
Example: npm install <package-
Installs the third-party packages
name> --save
//[Link]
3. Steps to create a Node JS Project
const path = require("path");
Run the below commands in the terminal.
const filePath = [Link]("users", "ravi", "[Link]");
1. Create a new directory/folder.
[Link](filePath);
mkdir myapp
JAVASCRIPT
2. Move into the created folder.
Output
cd myapp
root@123# node [Link]
3. Initialize the project.
users/ravi/[Link]
npm init -y
Note
4. Third-Party Packages
Many developers prefer Common JS Modules to ES6 syntax as ES6
syntax is in the experimental phase. The Third-Party Packages are the external Node JS Packages.
2. Package They are developed by Node JS developers and are made available
through the Node ecosystem.
A package is a directory with one or more modules grouped.
4.1 date-fns
2.1 Node Package Manager (NPM)
It is a third-party package for manipulating JavaScript dates in a o Server-side Web Frameworks
browser & [Link].
• Express JS
Installation Command: • Network Call using Express JS
npm install date-fns --save o Handling HTTP Request
4.1.1 addDays • Testing Network calls
It adds the specified number of days to the given date.
• Network Call to get a Today’s Date
Example:
• Network Call to get HTML content as an HTTP Response
//[Link]
o Sending file as an HTTP Response
const {addDays} = require('date-fns');
1. HTTP Server
const result = addDays(new Date(2021, 0, 11), 10);
• Works with the HTTP requests and responses
[Link](result); • Handles the different paths
JAVASCRIPT • Handles the query parameters
Output • Sends the content as HTML, CSS, etc. as an HTTP response
root@123# node [Link]
• Works with the databases
2021-01-21T00:00:00.000Z
1.1 Server-side Web Frameworks
Note
The Server-side Web Frameworks take care of all the above
While creating the requirements.
Date() Some of the Web Frameworks are:
object, we have to provide the month index from (0-11), whereas we • Express (Node JS)
will get the output considering Jan=1 and Dec=12.
• Django (Python)
• Ruby on Rails (Ruby)
• Spring Boot (Java)
Introduction to Express JS | Cheat Sheet
2. Express JS
Concepts in Focus It is a free and open-source Server-side Web Application Framework
• HTTP Server for Node JS.
It provides a robust set of features to build web and mobile const app = express();
applications quickly and easily.
[Link]("/", (request, response) => {
Installation Command: [Link]("Hello World!");
npm install express --save });
3. Network call using Express JS [Link](3000);
1. Creating Express server instance
JAVASCRIPT
const express = require("express");
Note
const app = express();
Whenever the code changes, we need to restart the server to reflect
JAVASCRIPT the changes we made.
2. Assigning a port number 4. Testing Network Calls
1 We can test the Network calls in two ways.
[Link](3000); 1. Browser Network Tab.
JAVASCRIPT
The app starts a server and listens on port
3000
for connections.
3.1 Handling HTTP Request
Syntax:
[Link](PATH, HANDLER)
• METHOD is an HTTP request method, in lowercase
like get, post, put, and delete
• PATH is a path on the server.
• HANDLER is the function executed when the PATH is matched
with the requested path.
3.1.1 GET Request
const express = require("express");
5. Network Call to get a Today’s Date
const express = require("express");
const app = express();
[Link]("/date", (request, response) => {
let date = new Date();
[Link](`Today's date is ${date}`);
});
[Link](3000);
JAVASCRIPT
1. Clicking the
Send Request
6. Network Call to get HTML content as an HTTP Response
in the
6.1 Sending file as an HTTP Response
[Link]
Syntax:
file.
[Link](PATH, {root: __dirname });
• PATH is a path to the file which we want to send.
• __dirname is a variable in Common JS Modules that returns the
path of the folder where the current JavaScript file is present.
const express = require("express");
const app = express();
[Link]("/page", (request, response) => { All the Network calls that we added are also the APIs.
[Link]("./[Link]", { root: __dirname }); 2. Database
}); Express apps can use any database supported by Node JS.
[Link](3000); There are many popular options, including SQLite, PostgreSQL,
JAVASCRIPT MySQL, Redis, and MongoDB.
3. SQLite
The SQLite provides a command-line tool sqlite3.
It allows the user to enter and execute SQL statements against an
Introduction to Express JS | Part 2 | Cheat Sheet
SQLite database.
Concepts in Focus
3.1 SQLite CLI
• Application Programming Interface (API)
3.1.1 Listing Existing Tables
• Database
The
• SQLite
.tables
o SQLite CLI
command is used to get the list of tables available in the SQLite
• SQLite Methods database.
o Open 3.1.2 Selecting Table Data
o Executing SQL Queries Syntax:
• SQL Third-party packages SELECT * from <table>
• Connecting SQLite Database from Node JS to get the books 4. SQLite Methods
from Goodreads Website
4.1 Open
o SQLite Database Initialization
The SQLite
o Goodreads Get Books API
open()
1. Application Programming Interface (API)
method is used to connect the database server and provides a
An API is a software intermediary that allows two applications to talk connection object to operate on the database.
to each other.
Syntax:
For example, OLA, and UBER use Google Maps API to provide their
open({
services.
filename: DATABASE_PATH, Installation Commands
driver: SQLITE_DATABASE_DRIVER, npm install sqlite --save
}); npm install sqlite3 --save
JAVASCRIPT 6. Connecting SQLite Database from Node JS to get the books from
It returns a promise object. On resolving the promise object, we will Goodreads Website
get the database connection object. 1. Install the SQL third-party packages
4.2 Executing SQL Queries sqlite
SQLite package provides multiple methods to execute SQL queries on and
a database. sqlite3
Some of them are: .
• all()
2. Initialize the SQLite Database
• get()
6.1 SQLite Database Initialization
• run()
const express = require("express");
• exec(), etc.
const path = require("path");
4.2.1 all()
const { open } = require("sqlite");
[Link](SQL_QUERY); const sqlite3 = require("sqlite3");
The const app = express();
all() const dbPath = [Link](__dirname, "[Link]");
method is used to get multiple rows of data.
let db = null;
5. SQL Third-party packages
const initializeDBAndServer = async () => {
We can use
try {
sqlite
db = await open({
and
filename: dbPath,
sqlite3 driver: [Link],
node packages to connect SQLite Database from Node JS. });
[Link](3000, () => { Concepts in Focus
[Link]("Server Running at [Link] • SQLite Methods
}); o get()
} catch (e) { o run()
[Link](`DB Error: ${[Link]}`); • Node JS Third-party packages
[Link](1); o Nodemon
} • GoodReads API
}; o Get Book
initializeDBAndServer(); o Add Book
JAVASCRIPT o Update Book
Collapse o Delete Book
6.2 Goodreads Get Books API o Get Author Books
[Link]("/books/", async (request, response) => { 1. SQLite Methods
const getBooksQuery = ` The SQLite package provides multiple methods to execute SQL
queries on a database.
SELECT
Some of them are:
*
• all()
FROM
• get()
book
ORDER BY • run()
book_id;`; • exec(), etc.
const booksArray = await [Link](getBooksQuery); 1.1 get()
The get() method is used to get a single row from the table.
[Link](booksArray);
Syntax:
});
[Link](SQL_QUERY);
1.2 run() The run() method is used to create or update table data.
Introduction to Express JS | Part 3 | Cheat Sheet
Syntax: [Link]("/books/:bookId/", async (request, response) => {
[Link](SQL_QUERY); const { bookId } = [Link];
2. Node JS Third-party packages const getBookQuery = `
2.1 Nodemon SELECT
The Nodemon is a tool that restarts the server automatically *
whenever we make changes in the file.
FROM
Installation Command:
book
npm install -g nodemon
WHERE
Note
book_id = ${bookId};`;
The -g indicates that the nodemon will be installed globally in the
const book = await [Link](getBookQuery);
environment.
[Link](book);
• While executing the file, replace the node with the nodemon.
For example, nodemon [Link] });
. JAVASCRIPT
3. GoodReads APIs Collapse
• Get Book Note
• Add Book Any string can be used as a path parameter.
• Update Book 3.2 Add Book
• Delete Book To add a book to the Database, you need to send a request body in
JSON format.
• Get Author Books
• The [Link]()is used to recognize the incoming request
3.1 Get Book
object as JSON Object and parses it.
We can use • The [Link] is used to get the HTTP Request body.
/books/:bookId/ [Link]("/books/", async (request, response) => {
as a path to identify a single book resource, where
const bookDetails = [Link];
bookId is a path [Link] example,In
const {
[Link] , the bookId is 1.
title, ${pages},
authorId, '${dateOfPublication}',
rating, '${editionLanguage}',
ratingCount, ${price},
reviewCount, '${onlineStores}'
description, );`;
pages, const dbResponse = await [Link](addBookQuery);
dateOfPublication, const bookId = [Link];
editionLanguage, [Link]({ bookId: bookId });
price, });
onlineStores,
} = bookDetails; JAVASCRIPT
const addBookQuery = ` Collapse
INSERT INTO The
book [Link]
(title,author_id,rating,rating_count,review_count,description,pages,da
provides the primary key of the new row inserted.
te_of_publication,edition_language,price,online_stores)
3.3 Update Book
VALUES
We can use
(
/books/:bookId/
'${title}',
as a path to identify a single book resource, where
${authorId},
:bookId
${rating},
is the path parameter.
${ratingCount},
For example,
${reviewCount},
[Link]
'${description}',
.
[Link]("/books/:bookId/", async (request, response) => { description='${description}',
const { bookId } = [Link]; pages=${pages},
const bookDetails = [Link]; date_of_publication='${dateOfPublication}',
const { edition_language='${editionLanguage}',
title, price=${price},
authorId, online_stores='${onlineStores}'
rating, WHERE
ratingCount, book_id = ${bookId};`;
reviewCount, await [Link](updateBookQuery);
description, [Link]("Book Updated Successfully");
pages, });
dateOfPublication, JAVASCRIPT
editionLanguage, Collapse
price, The [Link] provides the parameters passed through the
request.
onlineStores,
Note
} = bookDetails;
The strings sent through the APIs must be wrapped in quotes.
const updateBookQuery = `
3.4 Delete Book
UPDATE
book [Link]("/books/:bookId/", async (request, response) => {
SET const { bookId } = [Link];
title='${title}', const deleteBookQuery = `
DELETE FROM
author_id=${authorId},
book
rating=${rating},
WHERE
rating_count=${ratingCount},
book_id = ${bookId};`;
review_count=${reviewCount},
await [Link](deleteBookQuery); o REST API Principles
[Link]("Book Deleted Successfully"); 1. Get Books API
}); Let's see how to add Filters to Get Books API
JAVASCRIPT 1.1 Filtering Books
3.5 Get Author Books • Get a specific number of books
[Link]("/authors/:authorId/books/", async (request, response) => { • Get books based on search query text
const { authorId } = [Link]; • Get books in the sorted order
const getAuthorBooksQuery = ` 1.1.1 Get a specific number of books
SELECT To get specific number of books in certain range we use limit and
offset.
*
FROM Offset is used to specify the position from where rows are to be
selected.
book
Limit is used to specify the number of rows. and many more...
WHERE Query parameters starts with ? (question mark) followed by key value
author_id = ${authorId};`; pairs separated by & (ampersand)
const booksArray = await [Link](getAuthorBooksQuery); Example :
[Link](booksArray); [Link]
}); [Link]
[Link]
Note
REST APIs | Cheat Sheet • The query parameters are used to sort/filter resources.
Concepts in Focus • The path parameters are used to identify a specific resource(s)
• Get Books API 1.1.2 Get books based on search query text
o Filtering Books We provide query text to search_q key
• REST APIs search_q = potter
o Why Rest Principles? 1.1.3 Get books in the sorted order
We provide sorted order to order key JAVASCRIPT
Ascending: ASC DESCENDING: DESC Collapse
order = ASC Note
order = DESC We can skip or add slash while appending query parameters to the
Filtering GET Books API URL
[Link] is same as
[Link]("/books/", async (request, response) => {
[Link]
const {
2. REST APIs
offset = 2,
REST: Representational State Transfer
limit = 5,
REST is a set of principles that define how Web standards, such as
order = "ASC",
HTTP and URLs, are supposed to be used.
order_by = "book_id",
2.1 Why Rest Principles?
search_q = "",
Using Rest Principles improves application in various aspects like
} = [Link]; scalability, reliability etc
const getBooksQuery = ` 2.2 REST API Principles
SELECT • Providing unique ID to each resource
* • Using standard methods like GET, POST, PUT, and DELETE
FROM • Accept and Respond with JSON
book and many more...
WHERE
title LIKE '%${search_q}%'
ORDER BY ${order_by} ${order} Debugging Common Errors | Cheat Sheet
LIMIT ${limit} OFFSET ${offset};`; Concepts in Focus
const booksArray = await [Link](getBooksQuery); • Importing Unknown Modules
[Link](booksArray); • Starting Server in Multiple Terminals
}); • Starting Server outside the myapp
• Accessing Wrong URL at Module._compile (internal/modules/cjs/[Link]:30)
• Missing Function Call at [Link]._extensions..js
• Importing Unknown File (internal/modules/cjs/[Link]:10)
1. Importing Unknown Modules at [Link] (internal/modules/cjs/[Link]:32)
When we try to import unknown modules at [Link]._load (internal/modules/cjs/[Link]:14)
at [Link] [as runMain]
root@123:/.../myapp# nodemon [Link]
(internal/modules/run_main.js:71:12) {
[nodemon] 2.0.7
code: 'MODULE_NOT_FOUND',
[nodemon] to restart at any time, enter `rs`
requireStack: [
[nodemon] watching path(s): *.*
'/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part-
[nodemon] watching extensions: js,mjs,json 2/myapp/[Link]'
[nodemon] starting `node [Link]` ]
internal/modules/cjs/[Link] }
throw err; [nodemon] app crashed - waiting for file changes before starting...
^
Error: Cannot find module 'expresses' Collapse
Require stack: 2. Starting Server in Multiple Terminals
- /home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part- When we try to start the server in multiple terminals
2/myapp/[Link]
root@123:/.../myapp# nodemon [Link]
at [Link]._resolveFilename
[nodemon] 2.0.7
(internal/modules/cjs/[Link]:15)
[nodemon] to restart at any time, enter `rs`
at [Link]._load (internal/modules/cjs/[Link]:27)
at [Link] (internal/modules/cjs/[Link]:19) [nodemon] watching path(s): *.*
at require (internal/modules/cjs/[Link]:18) [nodemon] watching extensions: js,mjs,json
[nodemon] starting `node [Link]`
at Object.<anonymous>
(/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part- [Link]
2/myapp/[Link]:17)
throw er; // Unhandled 'error' event
^ Step 1: Kill the currently running process in the terminal with Ctrl +
C
Error: listen EADDRINUSE: address already in use :::3000
at [Link] [as _listen2] ([Link]:16) Step 2: Run
at listenInCluster ([Link]:12) lsof -i :port_number
at [Link] ([Link]:7) in your CCBP IDE Terminal
Step 3: Run
at [Link] (/home/workspace/nodejs/sessions/Introduction-
to-Express-JS-Part- kill -9 process_id
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres in your CCBP IDE Terminal
s/lib/[Link]:24)
Example :
at initializeDBAndServer
(/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part- root@123:/.../...part-3/myapp# nodemon [Link]
2/myapp/[Link]:9) [nodemon] starting `node [Link]`
Emitted 'error' event on Server instance at: [Link]
at emitErrorNT ([Link]:8) throw er; // Unhandled 'error' event
at processTicksAndRejections ^
(internal/process/task_queues.js:84:21) {
Error: listen EADDRINUSE: address already in use :::3000
code: 'EADDRINUSE',
.
errno: 'EADDRINUSE',
.
syscall: 'listen',
.
address: '::',
^C
port: 3000
root@123:/.../...part-3# lsof -i :3000
}
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE
[nodemon] app crashed - waiting for file changes before starting... NAME
node 9841 root 20u IPv6 345981 0t0 TCP *:3000 (LISTEN)
Collapse root@123:/.../...part-3# kill -9 9841
When you get address already in use :::3000 error root@123:/.../...part-3#
Collapse <html lang="en">
3. Starting Server outside the myapp <head>
When we try to start the server outside myapp using node <meta charset="utf-8">
root@123:/.../...part-3# node [Link] <title>Error</title>
internal/modules/cjs/[Link] </head>
throw err; <body>
^ <pre>Cannot GET /bookss/1/</pre>
Error: Cannot find module '/.../...Part-3/[Link]' </body>
root@123:/.../...part-3# </html
When we try to start the server outside myapp using nodemon Collapse
root@123:/.../...part-3# nodemon [Link] 5. Missing Function Call
Usage: nodemon [nodemon options] [[Link]] [args] When we miss calling the function express and trying to access
See "nodemon --help" for more. methods returned from the function express
root@123:/.../...part-3/myapp# nodemon [Link]
root@123:/.../...part-3#
[nodemon] 2.0.7
4. Accessing Wrong URL
[nodemon] to restart at any time, enter `rs`
When we try to Send Request for wrong URLs
[nodemon] watching path(s): *.*
HTTP/1.1 404 Not Found
[nodemon] watching extensions: js,mjs,json
X-Powered-By: Express
Content-Security-Policy: default-src 'none' [nodemon] starting `node [Link]`
X-Content-Type-Options: nosniff /home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part-
2/myapp/[Link]
Content-Type: text/html; charset=utf-8
[Link]("/books/", async (request, response) => {
Content-Length: 148
^
Date: Sun, 04 Apr 2021 11:50:56 GMT
TypeError: [Link] is not a function
Connection: close
<!DOCTYPE html>
at Object.<anonymous> function without a catch block, or by rejecting a promise which was
(/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part- not handled with .catch(). To terminate the node process on unhandled
2/myapp/[Link]:5) promise rejection, use the CLI flag `--unhandled-rejections=strict`
(see [Link]
at Module._compile (internal/modules/cjs/[Link]:30)
(rejection id: 1)
at [Link]._extensions..js
(node:668) [DEP0018] DeprecationWarning: Unhandled promise
(internal/modules/cjs/[Link]:10)
rejections are deprecated. In the future, promise rejections that are not
at [Link] (internal/modules/cjs/[Link]:32) handled will terminate the [Link] process with a non-zero exit code.
at [Link]._load (internal/modules/cjs/[Link]:14)
at [Link] [as runMain]
(internal/modules/run_main.js:71:12)
Debugging Common Errors | Part 2 | Cheat Sheet
at internal/main/run_main_module.js:17:47
Concepts in Focus
[nodemon] app crashed - waiting for file changes before starting...
• Request Methods
• Missing colon(:)
Collapse
• Accessing Path Parameters
6. Importing Unknown File
• Query Formatting
When we try to import an unknown file
• Replacing SQLite Methods
root@123:/.../...part-3/myapp# nodemon [Link]
• HTTP Request URL
[nodemon] 2.0.7
o Missing '?'
[nodemon] to restart at any time, enter `rs`
o Missing ‘&’ between Query Parameters
[nodemon] watching path(s): *.*
o Replacing '&' with ',' in Query Parameters
[nodemon] watching extensions: js,mjs,json
• Accessing Unknown Database
[nodemon] starting `node [Link]`
• Accessing Wrong Port Number
Server Running at [Link]
1. Request Methods
(node:668) UnhandledPromiseRejectionWarning: Error:
When we try to request with a wrong method
SQLITE_ERROR: no such table: book
HTTP/1.1 404 Not Found
(node:668) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async X-Powered-By: Express
Content-Security-Policy: default-src 'none' Date: Sun, 04 Apr 2021 11:50:56 GMT
X-Content-Type-Options: nosniff Connection: close
Content-Type: text/html; charset=utf-8 <!DOCTYPE html>
Content-Length: 148 <html lang="en">
Date: Sun, 04 Apr 2021 11:50:56 GMT <head>
Connection: close <meta charset="utf-8">
<!DOCTYPE html> <title>Error</title>
<html lang="en"> </head>
<head> <body>
<meta charset="utf-8"> <pre>Cannot GET /books/</pre>
<title>Error</title> </body>
</head> </html
<body> Collapse
<pre>Cannot POST /books/</pre> 3. Accessing Path Parameters
</body> When we are trying to access path parameters with the wrong name
</html root@123:/.../...part-3/myapp# nodemon [Link]
Collapse [nodemon] 2.0.7
2. Missing colon(:) [nodemon] to restart at any time, enter `rs`
When we miss semicolon while setting Path Parameters [nodemon] watching path(s): *.*
HTTP/1.1 404 Not Found [nodemon] watching extensions: js,mjs,json
X-Powered-By: Express [nodemon] starting `node [Link]`
Content-Security-Policy: default-src 'none' Server Running at [Link]
X-Content-Type-Options: nosniff (node:905) UnhandledPromiseRejectionWarning: ReferenceError:
bookId is not defined
Content-Type: text/html; charset=utf-8
Content-Length: 148
at /home/workspace/nodejs/sessions/Introduction-to-Express-JS- at Function.process_params
Part-2/myapp/[Link]:19 (/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres
at [Link] [as handle_request]
s/lib/router/[Link]:3)
(/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres at next (/home/workspace/nodejs/sessions/Introduction-to-Express-
s/lib/router/[Link]:5) JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres
at next (/home/workspace/nodejs/sessions/Introduction-to-Express-
s/lib/router/[Link]:10)
JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres (node:905) UnhandledPromiseRejectionWarning: Unhandled promise
s/lib/router/[Link]:13) rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
at [Link] (/home/workspace/nodejs/sessions/Introduction-
not handled with .catch(). To terminate the node process on unhandled
to-Express-JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres promise rejection, use the CLI flag `--unhandled-rejections=strict`
(see [Link]
s/lib/router/[Link]:3)
(rejection id: 1)
at [Link] [as handle_request]
(node:905) [DEP0018] DeprecationWarning: Unhandled promise
(/home/workspace/nodejs/sessions/Introduction-to-Express-JS-Part-
rejections are deprecated. In the future, promise rejections that are not
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres
s/lib/router/[Link]:5) handled will terminate the [Link] process with a non-zero exit code.
at /home/workspace/nodejs/sessions/Introduction-to-Express-JS-
Part- Collapse
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres
4. Query Formatting
s/lib/router/[Link]:22
When we miss embedding expression into string literal properly in the
at param (/home/workspace/nodejs/sessions/Introduction-to-
query
Express-JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres root@123:/.../...part-3/myapp# nodemon [Link]
s/lib/router/[Link]:14) [nodemon] 2.0.7
at param (/home/workspace/nodejs/sessions/Introduction-to- [nodemon] to restart at any time, enter `rs`
Express-JS-Part-
2/myapp/node_modules/.pnpm/express@4.17.1/node_modules/expres [nodemon] watching path(s): *.*
s/lib/router/[Link]:14) [nodemon] watching extensions: js,mjs,json
[nodemon] starting `node [Link]`
Server Running at [Link] "changes":0
(node:1023) UnhandledPromiseRejectionWarning: Error: }
SQLITE_ERROR: no such table: book Collapse
(node:1023) UnhandledPromiseRejectionWarning: Unhandled 6. HTTP Request URL
promise rejection. This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise 6.1 Missing
which was not handled with .catch(). To terminate the node process ?
on unhandled promise rejection, use the CLI flag `--unhandled-
rejections=strict` (see When we miss
[Link] ?
(rejection id: 1)
before starting query parameters
(node:1023) [DEP0018] DeprecationWarning: Unhandled promise
HTTP/1.1 404 Not Found
rejections are deprecated. In the future, promise rejections that are not
handled will terminate the [Link] process with a non-zero exit code. X-Powered-By: Express
Content-Security-Policy: default-src 'none'
5. Replacing SQLite Methods X-Content-Type-Options: nosniff
When we use one SQLite method instead of another SQLite method Content-Type: text/html; charset=utf-8
we may get an unexpected response Content-Length: 148
HTTP/1.1 200 OK Date: Sun, 04 Apr 2021 11:50:56 GMT
X-Powered-By: Express Connection: close
Content-Type: application/json; charset=utf-8 <!DOCTYPE html>
Content-Length: 34 <html lang="en">
ETag: W/"22-fiAy4921oZAEOAA97wnoLQyL2Dw" <head>
Date: Sun, 04 Apr 2021 12:46:07 GMT <meta charset="utf-8">
Connection: close <title>Error</title>
{ </head>
"stmt":{}, <body>
"lastID":0,
<pre>Cannot GET rejections=strict` (see
[Link] [Link]
r_by=price&order=DESC</pre> (rejection id: 1)
</body> (node:1408) [DEP0018] DeprecationWarning: Unhandled promise
rejections are deprecated. In the future, promise rejections that are not
</html
handled will terminate the [Link] process with a non-zero exit code.
Collapse
6.2 Missing
Collapse
&
6.3 Replacing & with , in Query Parameters When we replace &with
between Query Parameters ,in Query Parameters
When we miss root@123:/.../...part-3/myapp# nodemon [Link]
& [nodemon] 2.0.7
between query parameters [nodemon] to restart at any time, enter `rs`
root@123:/.../...part-3/myapp# nodemon [Link] [nodemon] watching path(s): *.*
[nodemon] 2.0.7 [nodemon] watching extensions: js,mjs,json
[nodemon] to restart at any time, enter `rs` [nodemon] starting `node [Link]`
[nodemon] watching path(s): *.* Server Running at [Link]
[nodemon] watching extensions: js,mjs,json string
[nodemon] starting `node [Link]` (node:1452) UnhandledPromiseRejectionWarning: Error:
Server Running at [Link] SQLITE_ERROR: near ",": syntax error
string (node:1452) UnhandledPromiseRejectionWarning: Unhandled
promise rejection. This error originated either by throwing inside of
(node:1408) UnhandledPromiseRejectionWarning: Error: an async function without a catch block, or by rejecting a promise
SQLITE_ERROR: unrecognized token: "3offset" which was not handled with .catch(). To terminate the node process
(node:1408) UnhandledPromiseRejectionWarning: Unhandled on unhandled promise rejection, use the CLI flag `--unhandled-
promise rejection. This error originated either by throwing inside of rejections=strict` (see
an async function without a catch block, or by rejecting a promise [Link]
which was not handled with .catch(). To terminate the node process (rejection id: 1)
on unhandled promise rejection, use the CLI flag `--unhandled-
(node:1452) [DEP0018] DeprecationWarning: Unhandled promise o Register User API
rejections are deprecated. In the future, promise rejections that are not
o Login User API
handled will terminate the [Link] process with a non-zero exit code.
1. Installing Third-party package bcrypt
Storing the passwords in plain text within a database is not a good
Collapse
idea since they can be misused, So Passwords should be encrypted
7. Accessing Unknown Database
bcrypt
When we are trying to access an unknown Database it will not show
package provides functions to perform operations like encryption,
any error instead it creates a new database with the given name
comparison, etc
• [Link]() uses various processes and encrypts the given
root@123:/.../myapp# sqlite3 [Link] password and makes it unpredictable
SQLite version 3.16.2 2017-01-06 16:32:41 • [Link]() function compares the password entered by
Enter ".help" for usage hints. the user and hash against each other
sqlite>.tables Installation Command
1
sqlite>
root@123:~/myapp# npm install bcrypt --save
8. Accessing Wrong Port Number
2. Goodreads APIs for Specified Users
When we are trying to access the wrong port number, we may get the
below notification We need to maintain the list of users in a table and provide access
1 only to that specified users
User needs to be registered and then log in to access the books
The connection was rejected. Either the requested service isn’t
running on the requested server/port, the proxy settings in vscode are • Register User API
misconfigured, or a firewall is blocking requests. Details:
• Login User API
RequestError: connect ECONNREFUSED [Link]:4000.
2.1 Register User API
Here we check whether the user is a new user or an existing user.
Authentication | Cheat Sheet
Returns "User Already exists" for existing user else for a new user we
Concepts in Focus store encrypted password in the DB
• Installing Third-party package bcrypt [Link]("/users/", async (request, response) => {
• Goodreads APIs for Specified Users
const { username, name, password, gender, location } = });
[Link];
JAVASCRIPT
const hashedPassword = await [Link]([Link], Collapse
10);
2.2 Login User API
const selectUserQuery = `SELECT * FROM user WHERE username
= '${username}'`; Here we check whether the user exists in DB or not. Returns "Invalid
User" if the user doesn't exist else we compare the given password
const dbUser = await [Link](selectUserQuery); with the DB user password
if (dbUser === undefined) {
[Link]("/login", async (request, response) => {
const createUserQuery = `
const { username, password } = [Link];
INSERT INTO
const selectUserQuery = `SELECT * FROM user WHERE username
user (username, name, password, gender, location) = '${username}'`;
VALUES const dbUser = await [Link](selectUserQuery);
( if (dbUser === undefined) {
'${username}', [Link](400);
'${name}', [Link]("Invalid User");
'${hashedPassword}', } else {
'${gender}', const isPasswordMatched = await [Link](password,
[Link]);
'${location}'
)`; if (isPasswordMatched === true) {
const dbResponse = await [Link](createUserQuery); [Link]("Login Success!");
const newUserId = [Link]; } else {
[Link](400);
[Link](`Created new user with ${newUserId}`);
[Link]("Invalid Password");
} else {
}
[Link] = 400;
}
[Link]("User already exists");
});
}
JAVASCRIPT To check whether the user is logged in or not we use different
Authentication mechanisms
Collapse
Status Codes Commonly used Authentication mechanisms:
• Token Authentication
Status Codes Status Text ID
• Session Authentication
200 OK 2. Token Authentication mechanism
204 No Response We use the Access Token to verify whether the user is logged in or not
301 Moved Permanently 2.1 Access Token
400 Bad Request Access Token is a set of characters which are used to identify a user
403 Forbidden Example:
401 Unauthorized It is used to verify whether a user is Valid/Invalid
2.2 How Token Authentication works?
• Server generates token and certifies the client
Authentication | Part 2 | Cheat Sheet • Client uses this token on every subsequent request
• Authentication Mechanisms • Client don’t need to provide entire details every time
• Token Authentication mechanism 3. JWT
o Access Token JSON Web Token is a standard used to create access tokens for an
application This access token can also be called as JWT Token
o How Token Authentication works?
3.1 How JWT works?
• JWT
Client: Login with username and password
o How JWT works?
Server: Returns a JWT Token
o JWT Package
Client: Sends JWT Token while requesting
• Login User API by generating the JWT Token
Server: Sends Response to the client
• How to pass JWT Token?
3.2 JWT Package
• Get Books API with Token Authentication 3.3 jsonwebtoken package provides [Link] and [Link]
1. Authentication Mechanisms functions
3.4 [Link]() function takes payload, secret key, options as [Link](400);
arguments and generates JWTToken out of it
[Link]("Invalid Password");
3.5 [Link]() verifies jwtToken and if it’s valid, returns payload.
Else, it throws an error }
root@123root@123:.../myapp# npm install jsonwebtoken }
4. Login User API by generating the JWT Token });
When the user tries to log in, verify the Password. Returns JWT JAVASCRIPT
Token if the password matches else return Invalid Password with Collapse
status code 400.
5. How to pass JWT Token?
[Link]("/login", async (request, response) => {
We have to add an authorization header to our request and the JWT
const { username, password } = [Link]; Token is passed as a Bearer token
const selectUserQuery = `SELECT * FROM user WHERE username GET
= '${username}'`; [Link]
const dbUser = await [Link](selectUserQuery); by=price&order=DESC
if (dbUser === undefined) { Authorization: bearer
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicmFodWwi
[Link](400);
LCJnZW5kZXIiOiJNYWxlIiwibG9jYXRpb24iOiJoeWRlcmFiYWQi
[Link]("Invalid User"); LCJpYXQiOjE2MTc0MzI0MDd9.Eqevw5QE70ZAVrmOZUc6pflUb
eI0ffZUmQLDHYplU8g
} else {
const isPasswordMatched = await [Link](password, 6. Get Books API with Token Authentication
[Link]); Here we check for JWT Token from Headers. If JWT Token is not
present it returns an Invalid Access Token with status code 401 else
if (isPasswordMatched === true) {
verify the JWT Token.
const payload = {
[Link]("/books/", (request, response) => {
username: username,
let jwtToken;
};
const authHeader = [Link]["authorization"];
const jwtToken = [Link](payload, "MY_SECRET_TOKEN");
if (authHeader !== undefined) {
[Link]({ jwtToken });
jwtToken = [Link](" ")[1];
} else {
} Authentication | Part 3 | Cheat Sheet
if (jwtToken === undefined) { • Middleware functions
[Link](401); o Multiple Middleware functions
[Link]("Invalid Access Token"); • Logger Middleware Implementation
} else { o Defining a Middleware Function
[Link](jwtToken, "MY_SECRET_TOKEN", async (error, o Logger Middleware Function
payload) => {
o Get Books API with Logger Middleware
if (error) {
• Authenticate Token Middleware
[Link]("Invalid Access Token");
• Get Books API with Authenticate Token Middleware
} else {
• Passing data from Authenticate Token Middleware
const getBooksQuery = ` • Get User Profile API with Authenticate Token Middleware
SELECT 1. Middleware functions
* Middleware is a special kind of function in Express JS which accepts
FROM the request from
book • the user (or)
ORDER BY • the previous middleware
book_id;`; After processing the request the middleware function
const booksArray = await [Link](getBooksQuery); • sends the response to another middleware (or)
[Link](booksArray); • calls the API Handler (or)
} • sends response to the user
}); [Link](Path, middleware1, handler);
} JAVASCRIPT
}); Example
JAVASCRIPT const jsonMiddleware = [Link]();
[Link](jsonMiddleware);
JAVASCRIPT *
It is a built-in middleware function it recognizes the incoming FROM
request object as a JSON object, parses it, and then calls handler in book
every API call
ORDER BY
1.1 Multiple Middleware functions
book_id;`;
We can pass multiple middleware functions
const booksArray = await [Link](getBooksQuery);
1
[Link](booksArray);
[Link](Path, middleware1, middleware2, handler);
});
JAVASCRIPT
JAVASCRIPT
2. Logger Middleware Implementation
Collapse
2.1 Defining a Middleware Function
3. Authenticate Token Middleware
1
In Authenticate Token Middleware we will verify the JWT Token
const middlewareFunction = (request, response, next) => {};
const authenticateToken = (request, response, next) => {
JAVASCRIPT
let jwtToken;
2.2 Logger Middleware Function
const authHeader = [Link]["authorization"];
const logger = (request, response, next) => {
if (authHeader !== undefined) {
[Link]([Link]);
jwtToken = [Link](" ")[1];
next();
}
};
if (jwtToken === undefined) {
JAVASCRIPT
[Link](401);
The next parameter is a function passed by Express JS which, when
invoked, executes the next succeeding function [Link]("Invalid JWT Token");
2.3 Get Books API with Logger Middleware } else {
[Link]("/books/", logger, async (request, response) => { [Link](jwtToken, "MY_SECRET_TOKEN", async (error,
payload) => {
const getBooksQuery = `
if (error) {
SELECT
[Link](401); 5. Passing data from Authenticate Token Middleware
[Link]("Invalid JWT Token"); We cannot directly pass data to the next handler, but we can send
} else { data through the request object
next(); const authenticateToken = (request, response, next) => {
} let jwtToken;
const authHeader = [Link]["authorization"];
});
if (authHeader !== undefined) {
}
jwtToken = [Link](" ")[1];
};
}
JAVASCRIPT
if (jwtToken === undefined) {
Collapse
4. Get Books API with Authenticate Token Middleware [Link](401);
Let's Pass Authenticate Token Middleware to Get Books API [Link]("Invalid JWT Token");
[Link]("/books/", authenticateToken, async (request, response) => { } else {
[Link](jwtToken, "MY_SECRET_TOKEN", async (error,
const getBooksQuery = `
payload) => {
SELECT
if (error) {
*
[Link](401);
FROM
[Link]("Invalid JWT Token");
book
} else {
ORDER BY
[Link] = [Link];
book_id;`;
next();
const booksArray = await [Link](getBooksQuery);
}
[Link](booksArray);
});
});
}
JAVASCRIPT
};
Collapse
JAVASCRIPT
Collapse
6. Get User Profile API with Authenticate Token Middleware
We can access request variable from the request object
[Link]("/profile/", authenticateToken, async (request, response) => {
let { username } = request;
const selectUserQuery = `SELECT * FROM user WHERE username
= '${username}'`;
const userDetails = await [Link](selectUserQuery);
[Link](userDetails);
});