Backend PPT
Backend PPT
● Node JS
● MySQL
● MongoDB
● Express JS
Table of Contents
● Introduction.
● Features.
● Node JS
● Node JS with MySQL
● Node JS with MongoDB
● Express JS
INTRODUCTION
• Node.js is a cross-platform runtime environment and library
for running JavaScript applications outside the browser. It is
used for creating server-side and networking web applications.
It is open source and free to use.
• Many of the basic modules of Node.js are written in JavaScript.
Node.js is mostly used to run real-time server applications.
• Node.js is a platform built on Chrome's JavaScript runtime for
easily building fast and scalable network applications. Node.js
uses an event-driven, non-blocking I/O model that makes it
lightweight and efficient, perfect for data-intensive real-time
applications that run across distributed devices.?
• Node.js also provides a rich library of various JavaScript
modules to simplify the development of web applications.
FEATURES
1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its library
is very fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are asynchronous
i.e. non-blocking. So a Node.js based server never waits for an API to return data. The
server moves to the next API after calling it and a notification mechanism of Events of
Node.js helps the server to get a response from the previous API call. It is also a reason
that it is very fast.
3. Single threaded: Node.js follows a single threaded model with event looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism helps the server
to respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while uploading audio and
video files. Node.js applications never buffer any data. These applications simply output
the data in chunks.
FIRST EXAMPLE
Node.js console-based Example
File: console_example1.js
node console_example1.js
FIRST EXAMPLE
Node.js web-based Example
A node.js web application contains the following three parts:
1. Import required module: The first step is to use ?require? directive to load http
module and store returned HTTP instance into http variable. For example:
2. Create server: In the second step, you have to use created http instance and call
http.createServer() method to create server instance and then bind it at port 8081 using
listen method associated with server instance. Pass it a function with request and
response parameters and write the sample implementation to return "Hello World". For
example:
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type':
'text/plain'});
response.end('Hello World\n');
}).listen(8081);
So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:
node main.js
Now server is started.
Open http://127.0.0.1:8081/ in any browser. You will see the following result.
NODE.JS CONSOLE
The Node.js console module provides a simple debugging
console similar to JavaScript console mechanism provided by
web browsers.
There are three console methods that are used to write any
node.js stream:
1. console.log()
2. console.error()
3. console.warn()
Node.js console.log()
The console.log() function is used to display simple message on console.
File: console_example1.js
node console_example1.js
We can also use format specifier in console.log() function.
File: console_example2.js
node console_example2.js
Node.js console.error()
The console.error() function is used to render error message on console.
File: console_example3.js
node console_example3.js
Node.js console.warn()
The console.warn() function is used to display warning message on console.
File: console_example4.js
node console_example4.js
NODE.JS REPL
The Node.js or node come bundled with REPL environment.
Each part of the REPL environment has a specific work.
Read: It reads user's input; parse the input into JavaScript
data-structure and stores in memory.
Eval: It takes and evaluates the data structure.
Print: It prints the result.
Loop: It loops the above command until user press ctrl-c
twice.
NODE.JS NPM
Node Package Manager provides two main functionalities:
The npm comes bundled with Node.js installables in versions after that
v0.6.3. You can check the version by opening Node.js command prompt and
typing the following command:
npm version
NODE.JS CL OPTIONS
To see the version of the running Node:
Open Node.js command prompt and run command node -v or node --
version
For Help:
Use command node ?h or node --help
NODE.JS GLOBALS
Node.js global objects are global in nature and available in all modules. You don't need to
include these objects in your application; rather they can be used directly. These objects are
modules, functions, strings and object etc. Some of these objects aren't actually in the global
scope but in the module scope.
A list of Node.js global objects are given below:
● __dirname
● __filename
● Console
● Process
● Buffer
● setImmediate(callback[, arg][, ...])
● setInterval(callback, delay[, arg][, ...])
● setTimeout(callback, delay[, arg][, ...])
● clearImmediate(immediateObject)
● clearInterval(intervalObject)
NODE.JS OS
In this example, we are including some basic functions. Create a file named os_example1.js
having the following code:
File: os_example1.js
const os=require('os');
console.log("os.freemem(): \n",os.freemem());
console.log("os.homedir(): \n",os.homedir());
console.log("os.hostname(): \n",os.hostname());
console.log("os.endianness(): \n",os.endianness());
console.log("os.loadavg(): \n",os.loadavg());
console.log("os.platform(): \n",os.platform());
console.log("os.release(): \n",os.release());
console.log("os.tmpdir(): \n",os.tmpdir());
console.log("os.totalmem(): \n",os.totalmem());
Open Node.js command prompt and run the following code:
node os_example1.js
NODE.JS TIMERS
Node.js Timer functions are global functions. You don't need to use require() function in order to
use timer functions. Let's see the list of timer functions.
File: error_example1.js
try {
const a = 1;
const c = a + b;
} catch (err) {
console.log(err);
}
NODE.JS DNS
The Node.js DNS module contains methods to get information of given
hostname. Let's see the list of commonly used DNS functions:
● dns.getServers()
● dns.setServers(servers)
● dns.lookup(hostname[, options], callback)
● dns.lookupService(address, port, callback)
● dns.resolve(hostname[, rrtype], callback)
● dns.resolve4(hostname, callback)
● dns.resolve6(hostname, callback)
● dns.resolveCname(hostname, callback)
NODE.JS DNS
Let's see the example of dns.lookup() function.
File: dns_example1.js
dns.lookup('www.boardinfinity.com',(err, addresses,
family) => {
console.log('addresses:', addresses);
console.log('family:',family);
});
NODE.JS NET
Node.js provides the ability to perform socket programming. We
can create chat application or communicate client and server
applications using socket programming in Node.js. The Node.js net
module contains functions for creating both servers and clients.
What is Hash
A hash is a fixed-length string of bits i.e. procedurally and deterministically
generated from some arbitrary block of source data.
What is HMAC
HMAC stands for Hash-based Message Authentication Code. It is a process
for applying a hash algorithm to both data and a secret key that results in a
single final hash.
NODE.JS TLS/SSL
TLS stands for Transport Layer Security. It is the successor to Secure
Sockets Layer (SSL). TLS along with SSL is used for cryptographic
protocols to secure communication over the web.
Syntax:
The tls module uses OpenSSL to attain Transport Layer Security and Secure Socket
Layer. TLS/SSL is a public/private key infrastructure. Each client and each server
must have a private key.
All severs and some clients need to have a certificate. Certificates are public keys
signed by a Certificate Authority or self-signed. To get certificate, you have to
create a "Certificate Signing Request" (CSR) file.
NODE.JS
DEBUGGER
Node.js provides a simple TCP based protocol and built-in debugging
client. For debugging your JavaScript file, you can use debug argument
followed by the js file name you want to debug.
Syntax:
Example:
If you make any error in your js file source code or provide a wrong
path on the Node.js command prompt then you will get the
following result.
NODE.JS PROCESS
Let's see the simple process example to print architecture, pid, platform
and version of the process.
File: process_example1.js
node process_example1.js
NODE.JS CHILD PROCESS
The Node.js child process module provides the ability to spawn child
processes in a similar manner to popen(3).
Syntax:
Parameters:
Buffer class is a global class. It can be accessed in application without importing buffer
module.
Create a buffer from string: Following is the syntax to create a Buffer from
a given string and optionally encoding type:
Syntax:
var fs = require("fs")
// Asynchronous read
if (err) {
return console.error(err);
});
// Synchronous read
console.log("Program Ended");
Node.js Open a file
Syntax:
Parameter explanation:
flags: Flag specifies the behavior of the file to be opened. All possible values have been
mentioned below.
mode: This sets the file mode (permission and sticky bits), but only if the file was created.
It defaults to 0666, readable and writable.
callback: This is the callback function which gets two arguments (err, fd).
Create a JavaScript file named "main.js" having the following code to open a file input.txt for
reading and writing.
File: main.js
var fs = require("fs");
if (err) {
return console.error(err);
});
Open Node.js command prompt and run the main.js:
node main.js
NODE.JS PATH
The Node.js path module is used to handle and transform files paths.
This module can be imported by using the following syntax:
Syntax:
// Normalization
console.log('normalization : ' +
path.normalize('/sssit/javatpoint//node/newfolder/tab/..'));
// Join
// Resolve
// Extension
const StringDecoder =
require('string_decoder').StringDecoder;
File: stringdecoder_example1.js
console.log(decoder.write(buf3));//prints: buffer
NODE.JS QUERY STRING
The Node.js Query String provides methods to deal with query string. It
can be used to convert query string into JSON object and vice-versa.
querystring = require('querystring');
const
obj1=querystring.parse('name=sonoo&company=javatpoint');
console.log(obj1);
NODE.JS ZLIB
The Node.js Zlib module is used to provide compression and
decompression (zip and unzip) functionalities. It is
implemented using Gzip and deflate/inflate.
The zlib module can be accessed using:
const fs = require('fs');
inp.pipe(gzip).pipe(out);
NODE.JS ASSERTION
The Node.js Assert is the most elementary way to write
tests. It provides no feedback when running your test unless
one fails. The assert module provides a simple set of
assertion tests that can be used to test invariants. The
module is intended for internal use by Node.js, but can be
used in application code via require ('assert').
However assert is not a testing framework and cannot be
used as general purpose assertion library.
Let's see a simple example of Node.js Assert.
File: assert_example1.js
return a + b;
V8 in Node.js
The Node.js V8 module represents interfaces and event specific to the
version of V8. It provides methods to get information about heap memory
through v8.getHeapStatistics() and v8.getHeapSpaceStatistics()
methods.
To use this module, you need to use require('v8').
const v8 = require('v8');
The v8.getHeapStatistics() method returns statistics about heap such as
total heap size, used heap size, heap size limit, total available size etc.
File: v8-example1.js
const v8 = require('v8');
console.log(v8.getHeapStatistics());
NODE.JS CALLBACKS
• Callback is an asynchronous equivalent for a function. It is called
at the completion of each task.
• In Node.js, callbacks are generally used. All APIs of Node are
written in a way to supports callbacks.
• For example: when a function start reading file, it returns the
control to execution environment immediately so that the next
instruction can be executed.
• In Node.js, once file I/O is complete, it will call the callback
function. So there is no blocking or wait for File I/O.
• This makes Node.js highly scalable, as it can process high
number of request without waiting for any function to return
result.
NODE.JS EVENTS
1. Create a text file named input.txt having the following content:
Javatpoint is an online platform providing self learning tutorials on
different technologies, in a very simple language.
2. Create a JavaScript file named main.js having the following code:
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
3. Open the Node.js command prompt and execute the following code.
node main.js
NODE.JS
EVENTS
In Node.js applications, Events and Callbacks concepts are used to provide
concurrency. As Node.js applications are single threaded and every API of
Node js are asynchronous. So it uses async function to maintain the
concurrency. Node uses observer pattern. Node thread keeps an event loop
and after the completion of any task, it fires the corresponding event which
signals the event listener function to get executed.
Assume if you search for mañana.com in your browser so your browser (which is
IDNA enabled) first convert this to punycode xn--maana-pta.com because the
character ñ is not allowed in regular domain name. It is not supported in older
versions.
Punycode.js is bundled with Node.js v0.6.2 and later versions. If you want to use it
with other Node.js versions then use npm to install punycode module first. You have
to use require ('punycode') to access it.
Syntax:
punycode = require('punycode');
NODE.JS TTY
The Node.js TTY module contains tty.ReadStream and tty.WriteStream
classes. In most cases, there is no need to use this module directly.
Syntax:
When Node.js discovers that it is being run inside a TTY context, then:
node -p -e "Boolean(process.stdout.isTTY)"
NODE.JS WEB MODULES
Web Server is a software program that handles HTTP requests sent
by HTTP clients like web browsers, and returns web pages in
response to the clients. Web servers usually respond with html
documents along with images, style sheets and scripts.
Most of the web server support server side scripts using scripting
language or redirect to application server which perform the specific
task of getting data from database, perform complex logic etc. and
then sends a result to the HTTP client through the Web server.
Apache web server is one of the most commonly used web server. It
is an open source project.
● Client Layer: The Client layer contains web browsers, mobile
browsers or applications which can make HTTP request to the
web server.
● Server Layer: The Server layer contains Web server which can
intercepts the request made by clients and pass them the
response.
● Business Layer: The business layer contains application server
which is utilized by web server to do required processing. This
layer interacts with data layer via database or some external
programs.
WEB MODULES
NEST JS
Once the MySQL is installed and running, you can access it by using Node.js.
To download and install the "mysql" module, open the Command Terminal and
execute the following:
host: "localhost",
user: "root",
password: "12345"
});
con.connect(function(err) {
console.log("Connected!");
});
Now open the command terminal and use the following
command:
Node connection.js
MySQL CREATE DATABASE
CREATE DATABASE statement is used to create a database in
MySQL.
Example
For creating a database named "Board Infinity".
Create a js file named boardinfinity.js having the following
data in DBexample folder.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE Board Infinity", function (err,
result) {
if (err) throw err;
console.log("Database created");
});
});
MySQL CREATE TABLE
CREATE TABLE command is used to create a table in
MySQL. You must make it sure that you define the name of
the database when you create the connection.
Example
For creating a table named "employees".
Create a js file named employees.js having the following
data in DBexample folder.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "Board Infinity"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE employees (id INT, name VARCHAR(255), age
INT(3), city VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Now open command terminal and run the following
command:
Node employees.js
MySQL INSERT RECORD
INSERT INTO statement is used to insert records in
MySQL.
Example
Insert Single Record:
Insert records in "employees" table.
Create a js file named "insert" in DBexample folder and
put the following data into it:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "Board Infinity"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO employees (id, name, age, city) VALUES
('1', 'Ajeet Kumar', '27', 'Allahabad')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
Now open command terminal and run the following
command:
Node insert.js
MySQL UPDATE RECORD
The UPDATE command is used to update records
in the table.
Example
Update city in "employees" table where id is 1.
Create a js file named "update" in DBexample
folder and put the following data into it:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "Board Infinity"
});
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE employees SET city = 'Delhi' WHERE city =
'Allahabad'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
Now open command terminal and run the following
command:
Node update.js
MySQL DELETE RECORD
The DELETE FROM command is used to delete
records from the table.
Example
Delete employee from the table employees where
city is Delhi.
Create a js file named "delete" in DBexample folder
and put the following data into it:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "Board Infinity"
});
con.connect(function(err) {
if (err) throw err;
var sql = "DELETE FROM employees WHERE city = 'Delhi'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
Now open command terminal and run the following
command:
Node delete.js
MySQL SELECT RECORD
Example
Retrieve all data from the table "employees".
Create a js file named select.js having the following data in DBexample folder.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "Board Infinity"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM employees", function (err, result) {
if (err) throw err;
console.log(result);
});
});
Now open command terminal and run the
following command:
Node select.js
MySQL SELECT UNIQUE
(WHERE Clause)
Retrieve a unique data from the table "employees".
Create a js file named select where.js having the
following data in DB example folder.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345",
database: "Board Infinity"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM employees WHERE id = '1'", function
(err, result) {
if (err) throw err;
console.log(result);
});
});
Now open command terminal and run the following
command:
Node drop.js
Node.JS
MongoDB
CREATE CONNECTION
MongoDb is a NoSQL database. It can be used with
Node.js as a database to insert and retrieve data.
Download MongoDB
Open the Linux Command Terminal and execute the
following command:
var url =
"mongodb://localhost:27017/MongoDatabase";
console.log("Database created!");
db.close();
});
Now open the command terminal and set the path
where Mongo Database exists. Now execute the
following command:
Node createdatabase.js
CREATE COLLECTION
MongoDB is a NoSQL database so data is stored in
collection instead of table. createCollection method is
used to create a collection in MongoDB.
Example
Create a collection named "employees".
Create a js file named "employees.js", having the
following data:
var MongoClient = require('mongodb').MongoClient;
console.log("Collection is created!");
db.close();
});
});
Open the command terminal and run the following
command:
Node employees.js
MongoDB INSERT
RECORD
The insertOne method is used to insert record in Mongo DB
collection. The first argument of the insertOne method is an
object which contains the name and value of each field in the
record you want to insert.
Example
(Insert Single record)
Insert a record in "employees" collection.
Create a js file named "insert.js", having the following code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/ MongoDatabase";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var myobj = [
{ name: "Mahesh Sharma", age: "25", address: "Ghaziabad"},
{ name: "Tom Moody", age: "31", address: "CA"},
{ name: "Zahira Wasim", age: "19", address: "Islamabad"},
{ name: "Juck Ross", age: "45", address: "London"}
];
db.collection("customers").insert(myobj, function(err, res) {
if (err) throw err;
console.log("Number of records inserted: " +
res.insertedCount);
db.close();
});
});
Open the command terminal and run the following
command:
console.log(result.name);
db.close();
});
});
Open the command terminal and run the following
command:
Node select.js
MongoDB QUERY
The find() method is also used to filter the result on a
specific parameter. You can filter the result by using a
query object.
Example
Filter the records to retrieve the specific employee whose
address is "Delhi".
Create a js file named "query1.js", having the following
code:
var http = require('http');
Node query1.js
MongoDB SORTING
In MongoDB, the sort() method is used for sorting the
results in ascending or descending order. The sort() method
uses a parameter to define the object sorting order.
{ name: 1 }
{ name: -1 }
Sort in Ascending Order
Example
Node sortasc.js
MongoDB REMOVE
In MongoDB, you can delete records or documents by
using the remove() method. The first parameter of the
remove() method is a query object which specifies the
document to delete.
Example
Remove the record of employee whose address is
Ghaziabad.
Create a js file named "remove.js", having the following
code:
var http = require('http');
db.close();
});
});
Open the command terminal and run the following
command:
Node remove.js
Express JS
EXPRESS JS INTRODUCTION
Express is a fast, assertive, essential and moderate web framework of
Node.js. You can assume express as a layer built on the top of the Node.js
that helps manage a server and routes. It provides a robust set of features
to develop web and mobile applications.
Let's see some of the core features of Express framework:
● It can be used to design single-page, multi-page and hybrid web
applications.
● It allows to setup middlewares to respond to HTTP Requests.
● It defines a routing table which is used to perform different actions
based on HTTP method and URL.
● It allows to dynamically render HTML Pages based on passing
arguments to templates.
EXPRESS JS FIRST
EXAMPLE
The express.js request object represents the HTTP request and has
properties for the request query string, parameters, body, HTTP
headers, and so on.
Syntax:
app.get('/', function (req, res) {
// --
})
Request Object Methods
Following is a list of some generally used request object methods:
req.accepts (types)
This method is used to check whether the specified content types are
acceptable, based on the request's Accept HTTP header field.
Examples:
req.accepts('html');
//=>?html?
req.accepts('text/html');
// => ?text/html?
req.get(field)
This method returns the specified HTTP request header field.
Examples:
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined
req.is(type)
This method returns true if the incoming request's "Content-Type" HTTP header
field matches the MIME type specified by the type parameter.
Examples:
req.is('html');
req.is('text/html');
req.is('text/*');
// => true
req.param(name [, defaultValue])
This method is used to fetch the value of param name when present.
Examples:
// ?name=sasha
req.param('name')
// => "sasha"
// POST name=sasha
req.param('name')
// => "sasha"
// /user/sasha for /user/:name
req.param('name')
// => "sasha"
EXPRESS JS
RESPONSE
The Response object (res) specifies the HTTP response which is sent by an
Express app when it gets an HTTP request.
What it does
res.append(field [, value])
This method appends the specified value to the HTTP response header field. That means if the
specified value is not appropriate then this method redress that.
Examples:
res.attachment([filename])
This method facilitates you to send a file as an attachment in the HTTP response.
Examples:
res.attachment('path/to/js_pic.png');
res.clearCookie(name [, options])
As the name specifies, the clearCookie method is used to clear the cookie
specified by name.
Examples:
To set a cookie
To clear a cookie:
This method transfers the file at path as an "attachment" and enforces the browser
to prompt user for download.
Example:
res.download('/report-12345.pdf');
res.end([data] [, encoding])
Response Format method
Syntax:
res.format(object)
Example:
res.format({
'text/plain': function(){
res.send('hey');
},
'text/html': function(){
res.send('
hey');
},
'application/json': function(){
res.send({ message: 'hey' });
},
'default': function() {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
}
});
Response JSONP method
Syntax:
res.jsonp([body])
Examples:
res.jsonp(null)
res.links(links)
This method populates the response?s Link HTTP header field by joining the links provided as properties of the
parameter.
Response Location method
Syntax:
res.location(path)
This method is used to set the response location HTTP header
field based on the specified path parameter.
Examples:
res.location('http://xyz.com');
Response Redirect method
Syntax:
res.redirect([status,] path)
This method redirects to the URL derived from the specified path, with specified HTTP status
Examples:
res.redirect('http://example.com');
This method renders a view and sends the rendered HTML string to the client.
Response Send method
Syntax:
res.send([body])
Examples:
res.send(new Buffer('whoop'));
res.send('
.....some html
');
Response sendFile method
Syntax:
This method is used to transfer the file at the given path. It sets the
Content-Type response HTTP header field based on the file name
extension.
Examples:
// ...
});
Response Set method
Syntax:
res.set(field [, value])
This method is used to set the response of HTTP header field to value.
Examples:
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
})
Response Status method
Syntax:
res.status(code)
This method sets an HTTP status for the response.
Examples:
res.status(403).end();
res.status(400).send('Bad Request');
Response Type method
Syntax:
res.type(type)
This method sets the content-type HTTP header to the MIME type.
Examples:
Express.js facilitates you to handle GET and POST requests using the instance of
express.
Get method facilitates you to send only limited amount of data because data is sent
in the header. It is not secure because data is visible in URL bar.
Express.js facilitates you to handle GET and POST requests using the
instance of express.
File: Index.html
<html>
<body>
</form>
</body>
</html>
EXPRESS JS ROUTING
Routing is made from the word route. It is used to
determine the specific behavior of an application. It
specifies how an application responds to a client
request to a particular route, URI or path and a specific
HTTP request method (GET, POST, etc.). It can handle
different types of HTTP requests.
Let's take an example to see basic routing.
var express = require('express');
res.send('Welcome to JavaTpoint!');
})
})
app.delete('/del_student', function (req, res) {
res.send('I am Deleted!');
})
})
// This responds a GET request for abcd, abxcd, ab123cd, and so
on
res.send('Pattern Matched.');
})
})
EXPRESS JS COOKIES
Cookies are small piece of information i.e. sent from a website and
stored in user's web browser when user browses that website. Every
time the user loads that website back, the browser sends that stored
data back to website or server, to recognize user.
Install cookie
You have to acquire cookie abilities in Express.js. So, install
cookie-parser middleware through npm by using the following
command:
Import cookie-parser into your app.
var express = require('express');
app.use(cookieParser());
Define a route:
Cookie-parser parses Cookie header and populate req.cookies with an object keyed by
the cookie names.
Let's define a new route in your express app like set a new cookie:
app.get('/cookie',function(req, res){
});
});
Browser sends back that cookie to the server, every time when it requests that website.
EXPRESS JS FILE
UPLOAD
In Express.js, file upload is slightly difficult because of its
asynchronous nature and networking approach.
It can be done by using middleware to handle multipart/form
data. There are many middleware that can be used like
multer, connect, body-parser etc.
Let's take an example to demonstrate file upload in Node.js.
Here, we are using the middleware 'multer'.
Create a folder "jtp file upload" having the following files:
uploads: It is an empty folder i.e. created to store the uploaded images.
{
"name": "file_upload",
"version": "0.0.1",
"dependencies": {
"express": "4.13.3",
"multer": "1.1.0"
},
"devDependencies": {
"should": "~7.1.0",
"mocha": "~2.3.3",
"supertest": "~1.1.0"
}
}
To install the package.json, execute the following
code:
npm install
EXPRESS JS
MIDDLEWARE
Express.js Middleware are different types of functions that are
invoked by the Express.js routing layer before the final request
handler.
As the name specified, Middleware appears in the middle
between an initial request and final intended route.
In stack, middleware functions are always invoked in the order in
which they are added.
Middleware is commonly used to perform tasks like body parsing
for URL-encoded or JSON requests, cookie parsing for basic
cookie handling, or even building JavaScript modules on the fly.
What is a Middleware function
Middleware functions are the functions that access to
the request and response object (req, res) in request-
response cycle.
A middleware function can perform the following tasks:
● It can execute any code.
● It can make changes to the request and the
response objects.
● It can end the request-response cycle.
● It can call the next middleware function in the stack.
Express.js Middleware
Following is a list of possibly used middleware in Express.js app:
● Application-level middleware
● Router-level middleware
● Error-handling middleware
● Built-in middleware
● Third-party middleware
res.send('Welcome to JavaTpoint!');
});
});
var server = app.listen(8000, function () {
})
You see that server is listening.
Now, you can see the result generated by server on the local
host http://127.0.0.1:8000
EXPRESS JS SCAFFOLDING
Scaffolding is a technique that is supported by some MVC frameworks.
Following is a list of some popular template engines that work with Express.js:
● https://nodejs.dev/learn/run-nodejs-scripts-from-the-command-line
● https://www.w3schools.com/nodejs/nodejs_mysql.asp
● https://docs.mongodb.com/drivers/node/current/
● https://www.w3schools.com/nodejs/nodejs_mongodb.asp
● https://www.npmjs.com/package/express
● https://www.tutorialspoint.com/expressjs/index.htm
ANY QUESTION ???
THANK YOU !!!