0% found this document useful (0 votes)
236 views

Lecture # 8 - Express - .Js

The document discusses Express.js, a web application framework for Node.js. It explains that Express.js provides a simple API to build websites and web apps without worrying about low-level protocols. It also discusses using Pug for templates, MongoDB and Mongoose for data storage, and creating a basic "Hello World" Express app. Finally, it covers topics like routers, HTTP methods, dynamic routes, and pattern matching routes.

Uploaded by

Danial Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
236 views

Lecture # 8 - Express - .Js

The document discusses Express.js, a web application framework for Node.js. It explains that Express.js provides a simple API to build websites and web apps without worrying about low-level protocols. It also discusses using Pug for templates, MongoDB and Mongoose for data storage, and creating a basic "Hello World" Express app. Finally, it covers topics like routers, HTTP methods, dynamic routes, and pattern matching routes.

Uploaded by

Danial Ahmad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Lecture # 8 – Express.

js

By Dr. Sidra Sultana


What is Express?
 ExpressJS is a web application framework.
 It provides you with a simple API to build websites, web
apps and back ends.
 With ExpressJS, you need not worry about low level
protocols, processes, etc.
Why Express?
 Unlike its competitors like Rails and Django, which have
an opinionated way of building applications, Express has
no "best way" to do something.
 It is very flexible and pluggable.
 Pug
 Pug (earlier known as Jade) is a terse language for writing
HTML templates. It −
 Produces HTML
 Supports dynamic code
 Supports reusability (DRY)
It is one of the most popular template language used with
Express.
MongoDB and Mongoose
 MongoDB is an open-source, document database designed
for ease of development and scaling. This database is also
used to store data.
 Mongoose is a client API for node.js which makes it easy
to access our database from our Express application.
ExpressJS - Hello World
 To install Express use the following command −
 npm install --s express
 This is all we need to start development using the Express
framework.
 To make our development process a lot easier, we will
install a tool from npm, nodemon.
 This tool restarts our server as soon as we make a change
in any of our files, otherwise we need to restart the server
manually after each file modification.
 To install nodemon, use the following command −
 npm install -g nodemon
ExpressJS - Hello World
 Create a new file called app.js and type the following in
it.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send("Hello world!"); });
app.listen(3000);
 Save the file, go to your terminal and type the following.
 nodemon app.js
 This will start the server.
 To test this app, open your browser and go
to http://localhost:3000
Output
How the App Works?
 The first line imports Express in our file, we have access to it
through the variable Express.
 We use it to create an application and assign it to var app.
 app.get(route, callback)
 This function tells what to do when a get request at the given
route is called.
 The callback function has parameters, 
request(req) and response(res). The
request object(req) represents the HTTP request and has
properties for the request query string, parameters, body, HTTP
headers, etc.
 Similarly, the response object represents the HTTP response that
the Express app sends when it receives an HTTP request.
How the App Works? Cont’d
 res.send()
 This function takes an object as input and it sends this to the
requesting client.
 Here we are sending the string "Hello World!".
How the App Works? Cont’d
 app.listen(port, [host], [backlog], [callback]])
 This function binds and listens for connections on the specified
host and port.
 Port is the only required parameter here.
S.No. Argument & Description
1 port
A port number on which the server should accept incoming requests.
2 host
Name of the domain. You need to set it when you deploy your apps to the
cloud.
3 backlog
The maximum number of queued pending connections. The default is 511.
4 callback
An asynchronous function that is called when the server starts listening for
requests.
How the App Works? Cont’d
 app.method(path, handler)
 This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete.
 An alternate method also exists, which executes independent of the request type.
 Path is the route at which the request will run.
 Handler is a callback function that executes when a matching request type is
found on the relevant route.
 For example,
var express = require('express');
var app = express();
app.get('/hello', function(req, res){
res.send("Hello World!"); });
app.listen(3000);
 If we run our application and go to localhost:3000/hello, the server receives a
get request at route "/hello", our Express app executes the callback function
attached to this route and sends "Hello World!" as the response.
How the App Works? Cont’d
 We can also have multiple different methods at the same
route. For example,
var express = require('express');
var app = express();
app.get('/hello', function(req, res){
res.send("Hello World!"); });
app.post('/hello', function(req, res){
res.send("You just called the post method at '/hello'!\n"); });
app.listen(3000);
How the App Works? Cont’d
 To test this request, open up your terminal and use cURL to
execute the following request −
 curl -X POST "http://localhost:3000/hello"
 A special method, all, is provided by Express to handle all
types of http methods at a particular route using the same
function.
 To use this method, try the following.

app.all('/test', function(req, res){


res.send("HTTP method doesn't have any effect on this
route!"); });
This method is generally used for defining middleware, which
we'll discuss in the middleware chapter.
Routers
 Defining routes like above is very tedious to maintain.
 To separate the routes from our main app.js file, we will
use Express.Router.
 Create a new file called things.js and type the following in
it.
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.send('GET route on things.'); });
router.post('/', function(req, res){
res.send('POST route on things.'); });
//export this router to use in our index.js module.exports = router;
Routers cont’d
 Now to use this router in our app.js, type in the following before
the app.listen function call.
var express = require('Express');
var app = express();
var things = require('./things.js');
//both index.js and things.js should be in same directory app.use('/things', things);
app.listen(3000);
 The app.use function call on route '/things' attaches the things router
with this route.
 Now whatever requests our app gets at the '/things', will be handled by
our things.js router.
 The '/' route in things.js is actually a subroute of '/things'.
 Visit localhost:3000/things/ and you will see the following output.
Output
Routers cont’d
 Routers are very helpful in separating concerns and keep
relevant portions of our code together.
 They help in building maintainable code.
 You should define your routes relating to an entity in a
single file and include it using the above method in
your app.js file.
ExpressJS - HTTP Methods
 The HTTP method is supplied in the request and specifies
the operation that the client has requested. The following
table lists the most used HTTP methods −
S.No. Method & Description
1 GET
The GET method requests a representation of the specified resource. Requests using GET should
only retrieve data and should have no other effect.

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

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

4 DELETE
The DELETE method requests that the server delete the specified resource.
ExpressJS - URL Building
 To use the dynamic routes, we SHOULD provide different
types of routes.
 Using dynamic routes allows us to pass parameters and
process based on them.
 Here is an example of a dynamic route −
var express = require('express');
var app = express();
app.get('/:id', function(req, res){
res.send('The id you specified is ' + req.params.id); }); app.listen(3000);
 To test this go to http://localhost:3000/123. The
following response will be displayed.
Output
ExpressJS - URL Building cont’d
 You can replace '123' in the URL with anything else and
the change will reflect in the response.
 A more complex example of the above is −
var express = require('express');
var app = express();
app.get('/things/:name/:id', function(req, res) {
res.send('id: ' + req.params.id + ' and name: ' + req.params.name); });
app.listen(3000);
To test the above code, go
to http://localhost:3000/things/tutorialspoint/12345.
Output
Pattern Matched Routes
 You can also use regex to restrict URL parameter
matching. Let us assume you need the id to be a 5-digit
long number. You can use the following route definition −
var express = require('express');
var app = express();
app.get('/things/:id([0-9]{5})', function(req, res){
res.send('id: ' + req.params.id); });
app.listen(3000);
Output
Pattern Matched Routes
 Note that this will only match the requests that have a 5-digit
long id.
 You can use more complex regexes to match/validate your
routes.
 If none of your routes match the request, you'll get a "Cannot
GET <your-request-route>" message as response.
 This message be replaced by a 404 not found page using this
simple route −
 //Other routes here
app.get('*', function(req, res){
res.send('Sorry, this is an invalid URL.'); });
Output
 Important − This should be placed after all your routes,
as Express matches routes from start to end of
the app.js file, including the external routers you required.
 For example, if we define the same routes as above, on
requesting with a valid URL, the following output is
displayed. −
ExpressJS - 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.
 These functions are used to modify req and res objects for
tasks like parsing request bodies, adding response headers,
etc.
ExpressJS – Middleware cont’d
 Here is a simple example of a middleware function in action −

var express = require('express');


var app = express();
//Simple request time logger
app.use(function(req, res, next){
console.log("A new request received at " + Date.now());
//This function call is very important. It tells that more processing is //required for //the current
request and is in the next middleware
//function/route handler.
next(); });
app.listen(3000);

 The above middleware is called for every request on the server.


 So after every request, we will get the following message in the console −
 A new request received at 1467267512545
ExpressJS – Middleware cont’d
 To restrict it to a specific route (and all its subroutes),
provide that route as the first argument of app.use().
 For Example,
var express = require('express');
var app = express();
//Middleware function to log request protocol
app.use('/things', function(req, res, next){
console.log("A request for things received at " + Date.now());
next(); });
// Route handler that sends the response
app.get('/things', function(req, res){ res.send('Things'); });
app.listen(3000);
Order of Middleware Calls
 One of the most important things about middleware in
Express is the order in which they are written/included in
your file;
 the order in which they are executed, given that the route
matches also needs to be considered.
 For example, in the following code snippet, the first
function executes first, then the route handler and then the
end function.
 This example summarizes how to use middleware before
and after route handler; also how a route handler can be
used as a middleware itself.
Order of Middleware Calls cont’d
var express = require('express');
var app = express();
//First middleware before response is sent
app.use(function(req, res, next){
console.log("Start"); next(); });
//Route handler
app.get('/', function(req, res, next){ res.send("Middle"); next(); });
app.use('/', function(req, res){
console.log('End'); });
app.listen(3000);
Order of Middleware Calls cont’d
 The following diagram summarizes what we have learnt
about middleware −
Third Party Middleware
 A list of Third party middleware for Express is available.
 Following are some of the most commonly used middleware; we will also
learn how to use/mount these −
 body-parser
 This is used to parse the body of requests which have payloads attached to them.
 To mount body parser, we need to install it using 
 npm install --save body-parser
 and to mount it, include the following lines in your index.js −
var bodyParser = require('body-parser');
//To parse URL encoded data
app.use(bodyParser.urlencoded({ extended: false }))
//To parse json data
app.use(bodyParser.json())
 To view all available options for body-parser, visit its github page.
Third Party Middleware cont’d
 cookie-parser
 It parses Cookie header and populate req.cookies with an object
keyed by cookie names.
 To mount cookie parser, we need to install it using
 npm install --save cookie-parser
 and to mount it, include the following lines in your index.js −
 var cookieParser = require('cookie-parser');
app.use(cookieParser())
Third Party Middleware cont’d
 express-session
 It creates a session middleware with the given options.
 We will discuss its usage in the Sessions section.
 We have many other third party middleware in ExpressJS.
 However, we have discussed only a few important ones
here.

You might also like