0% found this document useful (0 votes)
43 views41 pages

WT Unit-3 Express Js

Uploaded by

KAVAL VYAS
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)
43 views41 pages

WT Unit-3 Express Js

Uploaded by

KAVAL VYAS
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/ 41

Web Technology (WT)

(2101CS304)

Unit-03
ExpressJS

Prof. Arjun V. Bala


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9624822202
 Outline
Looping

ExpressJS
Serving Static Resources
Database Connectivity
API Using NodeJS
ExpressJS
 Express js is a very popular web application framework built to create Node.js Web based
applications.
 It provides an integrated environment to facilitate rapid development of Node based Web
applications.
 Express framework is based on Connect middleware engine and used Jade html template
framework for HTML templating.
 Core features of Express framework:
 Allows to set up middlewares to respond to HTTP Requests.
 Defines a routing table which is used to perform different action based on HTTP method and URL.
 Allows to dynamically render HTML Pages based on passing arguments to templates.
 Installing Express
npm install express

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 3


First web app with Express
app.js
1 const express = require('express');
2 const app = express();
3
4 app.get('/', function (req, res) {
5 res.send('Hello World!');
6 });
7
8 app.listen(3000, function () {
9 console.log('app.js listening to http://localhost:3000/');
10 });

 To run the file we will use following command


node app.js

 Then, load http://localhost:3000 in a browser to see the output.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 4


Basic Routing
 Routing refers to determining how an application responds to a client request to a particular
endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so
on).
 Each route can have one or more handler functions, which are executed when the route is
matched.
 Route definition takes the following structure:
app.METHOD(PATH, HANDLER);
 Where:
 app is an instance of express.
 METHOD is an HTTP request method, in lower case.
 PATH is a path on the server
 HANDLER is the function executed when the route is matched.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 5


Route methods
 A route method is derived from one of the HTTP methods, and is attached to an instance of
the express class.
 The following code is an example of routes that are defined for the GET and POST methods
to the root of the app.
 GET method route:
1 app.get('/', function (req, res) {
2 res.send('Get request to the homepage');
3 });

 POST method route:


1 app.post('/', function (req, res) {
2 res.send('Post request to the hmoepage');
3 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 6


Route methods (Cont.)
 There is a special routing method, app.all(), which is not derived from any HTTP method.
 This method is used for loading middleware functions at a path for all request methods.
 In the following example, the handler will be executed for requests to “/secret” whether you
are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in
the http module.
1 app.all('/secret', function (req, res, next) {
2 console.log('Accessing the secret section ...');
3 next(); // pass control to the next handler
4 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 7


Route paths
 Route paths, in combination with a request method, define the endpoints at which requests
can be made.
 Route paths can be strings, string patterns, or regular expressions.
 The characters ?, +, *, and () are subsets of their regular expression counterparts.
 The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
 NOTE: Query strings are not part of the route path.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 8


Route paths based on strings
 This route path will match requests to the root route, /.
1 app.get('/', function (req, res) {
2 res.send('root');
3 });

 This route path will match requests to /about.


1 app.get('/about', function (req, res) {
2 res.send('about');
3 });

 This route path will match requests to /random.text.


1 app.get('/random.text', function (req, res) {
2 res.send('random.text');
3 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 9


Route paths based on string patterns
 This route path will match acd and abcd.
app.get('/ab?cd', function(req, res) { res.send('ab?cd'); });
 This route path will match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', function(req, res) { res.send('ab+cd'); });
 This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.
app.get('/ab*cd', function(req, res) { res.send('ab*cd'); });
 This route path will match /abe and /abcde.
app.get('/ab(cd)?e', function(req, res) { res.send('ab(cd)?e'); });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 10


Route paths based on regular expressions
 This route path will match anything with an “a” in the route name.
1 app.get(/a/, function(req, res) {
2 res.send('/a/');
3 });

 This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and
so on.
1 app.get(/*fly$/, function(req, res) {
2 res.send('/*fly$/');
3 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 11


Route Parameters
 Route parameters are named URL segments that are used to capture the values specified at
their position in the URL. The captured values are populated in the req.params object, with
the name of the route parameter specified in the path as their respective keys.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
 To define routes with route parameters, simply specify the route parameters in the path of the
route as shown below.
1 app.get('/users/:userId/books/:bookId', function(req, res) {
2 res.send(req.params);
3 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 12


Route Parameters (Cont.)
 Since the hyphen (-) and the dot (.) are interpreted literally, they can be used along with route
parameters for useful purposes.
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }

Route path: /floats/:digit.:decimal


Request URL: http://localhost:3000/floats/123.45
req.params: { "digit": "123", "decimal": "45" }
 NOTE: The name of route parameters must be made up of “word characters” ([A-Za-z0-9_]).

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 13


Route Handlers
 You can provide multiple callback functions that behave like middleware to handle a request.
The only exception is that these callbacks might invoke next('route') to bypass the remaining
route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass
control to subsequent routes if there’s no reason to proceed with the current route.
 Route handlers can be in the form of a function, an array of functions, or combinations of
both.
 More than one callback function can handle a route (make sure you specify the next object).
For1 example:
app.get('/example/b',
2 function (req, res, next) {
3 console.log('the response will be sent by the next function ...');
4 next();
5 }, function (req, res) {
6 res.send('Hello from B!');
7 }
8 );

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 14


Route Handlers (Cont.)
 An array of callback functions can handle a route. For example:
var cb0 = function (req, res, next) { console.log('CB0'); next(); }
var cb1 = function (req, res, next) { console.log('CB1'); next(); }
var cb2 = function (req, res) { res.send('Hello from C!'); }
app.get('/example/c', [cb0, cb1, cb2]);
 A combination of independent functions and arrays of functions can handle a route. For
example:
var cb0 = function (req, res, next) { console.log('CB0'); next(); }
var cb1 = function (req, res, next) { console.log('CB1'); next(); }
app.get('/example/d', [cb0, cb1], function (req, res, next) {
console.log('the response will be sent by the next function ...');
next();
}, function (req, res) { res.send('Hello from D!'); });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 15


Response Methods
 The methods on the response object (res) in the following table can send a response to the
client, and terminate the request-response cycle. If none of these methods are called from a
route handler, the client request will be left hanging.
Method Description
res.download() Prompt a file to be downloaded.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a review template.
res.write() Write into output stream. (will not terminate req-res cycle, must write end method after
writing)
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.
res.end() End the response process.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 16


Express Middleware
 Middleware functions are functions that have access to the request object (req), the response
object (res), and the next middleware function in the application’s request-response cycle.
The next middleware function is commonly denoted by a variable named next.
 Middleware functions can perform the following tasks:
 Execute any code.
 Make changes to the request and the response objects.
 End the request-response cycle.
 Call the next middleware in the stack.
 If the current middleware function does not end the request-response cycle, it must
call next() to pass control to the next middleware function. Otherwise, the request will be left
hanging.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 17


Express Middleware (Cont.)
 The following shows the elements of a middleware function call:
var express = require('express');
var app = express();
app.get('/', function(req, res, next) {
next();
});
app.listen(3000);
 Where
 get: HTTP method for which the middleware function applies.
 '/': Path (route) for which the middleware function applies.
 function (): The middleware function.
 req: HTTP request argument to the middleware function.
 res: HTTP response argument to the middleware function.
 next: Callback argument to the middleware function.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 18


app.use() method
 app.use([path,] function [, function...])
 Mounts the specified middleware function or functions at the specified path. If path is not specified, it
defaults to '/'.
 NOTE: A route will match any path that follows its path immediately with a “/”. For example,
app.use('/apple', …) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.
 Example:
app.use('/admin', function(req, res, next) {
// GET 'http://www.example.com/admin/new'
console.log(req.originalUrl); // '/admin/new'
console.log(req.baseUrl); // '/admin'
console.log(req.path); // '/new'
next();
});
 Mounting a middleware function at a path will cause the middleware function to be executed
whenever the base of the requested path matches the path.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 19


app.use() method (Cont.)
 Since path defaults to “/”, middleware mounted without a path will be executed for every
request to the app.
// this middleware will be executed for every request to the app
app.use(function (req, res, next) {
console.log('Time: %d', Date.now());
next();
});
 Middleware functions are executed sequentially, therefore, the order of middleware inclusion
is important:
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) { res.send('Hello World'); });
// requests will never reach this route
app.get('/', function (req, res) { res.send('Welcome'); });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 20


Using Middleware
 An Express application can use the following types of middleware:
 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 21


Application-level Middleware
 Bind application-level middleware to an instance of the app object by using
the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the
request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
 Below example shows a middleware function mounted on the /user/:id path. The function is
executed for any type of HTTP request on the /user/:id path.
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method);
next();
});
 Below example shows a route and its handler function (middleware system). The function
handles GET requests to the /user/:id path.
app.get('/user/:id', function (req, res, next) { res.send('USER'); });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 22


Application-level Middleware (Cont.)
 Here is an example of loading a series of middleware functions at a mount point, with a
mount path. It illustrates a middleware sub-stack that prints request info for any type of
HTTP request to the /user/:id path.
app.use('/user/:id', function(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}, function (req, res, next) {
console.log('Request Type:', req.method);
next();
});

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 23


Application-level Middleware (Cont.)
 Route handlers enable you to define multiple routes for a path. The example below defines
two routes for GET requests to the /user/:id path.
 The second route will not cause any problems, but it will never get called because the first
route ends the request-response cycle.
 This example shows a middleware sub-stack that handles GET requests to the /user/:id path.
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id); next();
}, function (req, res, next) { res.send('User Info'); });
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next)
{ res.end(req.params.id); });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 24


Application-level Middleware (Cont.)
 To skip the rest of the middleware functions from a router middleware stack,
call next('route') to pass control to the next route.
 NOTE: next('route') will work only in middleware functions that were loaded by using
the app.METHOD() or router.METHOD() functions.
 This example shows a middleware sub-stack that handles GET requests to the /user/:id path.
app.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next route
if (req.params.id == 0) next('route');
// otherwise pass the control to the next middleware function in this stack
else next(); //
}, function (req, res, next) {
res.end('regular'); // render a regular page
});
// handler for the /user/:id path, which renders a special page
app.get('/user/:id', function (req, res, next) { res.end('special'); });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 25


Express Routers
 A router object is an isolated instance of middleware and routes. You can think of it as a
“mini-application,” capable only of performing middleware and routing functions. Every
Express application has a built-in app router.
 A router behaves like middleware itself, so you can use it as an argument to app.use() or as
the argument to another router’s use() method.
 The top-level express object has a Router() method that creates a new router object.
var express = require('express');
var app = express();
var router = express.Router();

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 26


Express Routers (Cont.)
 Once you’ve created a router object, you can add middleware and HTTP method routes (such
as get, put, post, and so on) to it just like an application. For example:
// invoked for any requests passed to this router
router.use(function(req, res, next) {
// .. some logic here .. like any other middleware
next(); });
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
// .. });
 You can then use a router for a particular root URL in this way separating your routes into
files or even mini-apps.
// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 27
Router Methods
 router.all(path, [callback, …] callback)
 This method is extremely useful for mapping “global” logic for specific path prefixes or
arbitrary matches. For example, if you placed the following route at the top of all other route
definitions, it would require that all routes from that point on would require authentication,
and automatically load a user. Keep in mind that these callbacks do not have to act as end
points; loadUser can perform a task, then call next() to continue matching subsequent routes.
router.all('*', requireAuthentication, loadUser);
 Another example of this is white-listed “global” functionality. Here the example is much like
before, but it only restricts paths prefixed with “/api”:
router.all('/api/*', requireAuthentication);

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 28


Router Methods (Cont.)
 router.METHOD(path, [callback, ...] callback)
 The router.METHOD() methods provide the routing functionality in Express, where
METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase.
Thus, the actual methods are router.get(), router.post(), router.put(), and so on.
 You can provide multiple callbacks, and all are treated equally, and behave just like
middleware, except that these callbacks may invoke next('route') to bypass the remaining
route callback(s). You can use this mechanism to perform pre-conditions on a route then pass
control to subsequent routes when there is no reason to proceed with the route matched.
router.get('/', function(req, res){
res.send('hello world');
});

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 29


Router Methods (Cont.)
 router.use([path], [function, ...] function)
 Uses the specified middleware function or functions, with optional mount path path, that
defaults to “/”.
 Middleware is like a plumbing pipe: requests start at the first middleware function defined
and work their way “down” the middleware stack processing for each path they match.
 The order in which you define middleware with router.use() is very important. They are
invoked sequentially, thus the order defines middleware precedence. For example, usually a
logger is the very first middleware you would use, so that every request gets logged.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 30


Router-level Middleware
 Router-level middleware works in the same way as application-level middleware, except it is
bound to an instance of express.Router().
var router = express.Router();
 Load router-level middleware by using the router.use() and router.METHOD() functions.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 31


Built-in Middleware
 Starting with version 4.x, Express no longer depends on Connect. With the exception
of express.static, all of the middleware functions that were previously included with Express’
are now in separate modules.
 The only built-in middleware function in Express is express.static. This function is based
on serve-static, and is responsible for serving static assets such as HTML files, images, and
so on.
 The function signature is:
express.static(root, [options])
 The root argument specifies the root directory from which to serve static assets.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 32


Built-in Middleware (Cont.)
 Here is an example of using the express.static middleware function with an elaborate options
object:
var options = { dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
}
app.use(express.static('public', options));
 You can have more than one static directory per app:
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 33


Serving Static files in Express
 To serve static files such as images, CSS files, and JavaScript files, use
the express.static built-in middleware function in Express.
 Pass the name of the directory that contains the static assets to the express.static middleware
function to start serving the files directly. For example, use the following code to serve
images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'));
 Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
 To use multiple static assets directories, call the express.static middleware function multiple
times:
app.use(express.static('public'));
app.use(express.static('files'));
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 34
Serving Static files in Express (Cont.)
 Express looks up the files in the order in which you set the static directories with
the express.static middleware function.
 To create a virtual path prefix (where the path does not actually exist in the file system) for
files that are served by the express.static function,specify a mount path for the static
directory, as shown below:
app.use('/static', express.static('public'));
 Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
 However, the path that you provide to the express.static function is relative to the directory
from where you launch your node process. If you run the express app from another directory,
it’s safer to use the absolute path of the directory that you want to serve:
app.use('/static', express.static(__dirname + '/public'));
Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 35
Creating REST API using Node, Express and MongoDB
 We are going to use mongoose package to connect with the mongoDB database.
 To install mongoose we need to install it using below command,
npm install mongoose

 We first need to create a Mongoose Schema,


models/Faculty.js
1 const mongoose = require('mongoose');
2
3 const schema = mongoose.Schema({
4 FacultyID: Number,
5 FacultyName: String,
6 FacultyInitial: String,
7 })
8
9 module.exports = mongoose.model("Faculty",schema);

 Here we need to set the schema as per our API fields.


 Next we will connect with the mongoDB and create REST API.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 36


Rest API (Cont.)
Faculty.js
1 const express = require("express");
2 const mongoose = require("mongoose");
3 const bodyParser = require("body-parser");
4 const Faculty = require('./models/Faculty.js');
5
6 // Connect to MongoDB database
7 mongoose
8 .connect("MongoDB Connection URL Here", { useNewUrlParser: true })
9 .then(() => {
10 const app = express();
11 app.use(bodyParser.urlencoded({ extended: false }))
12
13 // We will write code for all the routes & code here
14 // I will write different routes in different code snippet in following slides
15 // you need to add those snippets here
16
17 app.listen(3000, () => {
18 console.log("Server has started!")
19 })
20 })

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 37


Rest API (Cont.) (getAll, getByID and insert)
1 // get all faculties
2 app.get('/faculties',async (req,res)=>{
3 faculties = await Faculty.find();
4 res.send(faculties);
5 });
6
7 // get faculties by id
8 app.get('/faculties/:id',async (req,res)=>{
9 faculties = await Faculty.findOne({FacultyID:req.params.id});
10 res.send(faculties);
11 });
12
13 // add/insert new faculty
14 app.post('/faculties',async (req,res)=>{
15 const faculty = new Faculty({
16 FacultyID: req.body.FacultyID,
17 FacultyName: req.body.FacultyName,
18 FacultyInitial: req.body.FacultyInitial
19 })
20 await faculty.save()
21 res.send(faculty)
22 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 38


Rest API (Cont.) (Update by ID)
1 // update faculty by id
2 app.patch('/faculties/:id',async (req,res)=>{
3 try {
4 const faculty = await Faculty.findOne({FacultyID:req.params.id})
5
6 faculty.FacultyID = req.body.FacultyID;
7 faculty.FacultyName = req.body.FacultyName;
8 faculty.FacultyInitial = req.body.FacultyInitial;
9
10 await faculty.save()
11 res.send(faculty)
12 } catch {
13 res.status(404)
14 res.send({ error: "Faculty doesn't exist!" })
15 }
16 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 39


Rest API (Cont.) (Delete by ID)
1 // delete faculty by id
2 app.delete('/faculties/:id',async (req,res)=>{
3 try {
4 const faculty = await Faculty.findOne({FacultyID:req.params.id})
5 await faculty.delete()
6 res.send(faculty)
7 } catch {
8 res.status(404)
9 res.send({ error: "Faculty doesn't exist!" })
10 }
11 });

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 40


References
 Node.js the Right Way, Jim R. Wilson, The Programatic Bookshelf, ISBN 978-1-937785-73-4
 NodeJS: Practical Guide for Beginners, Matthew Gimson, ISBN 978-1-519354-07-5
 Express.js: Node.js Framework for Web Application Development, Daniel Green, ISBN 978-
1-530204-06-9
 Express.com
 GeeksForGeeks
 Tutorials Point
 The Node Beginner Book, Manuel Kiessling, Leanpub.

Prof. Arjun V. Bala #2101CS304 (WT)  Unit 03 – ExpressJS 41

You might also like