0% found this document useful (0 votes)
17 views22 pages

Express.js: Node.js Web Framework Guide

Uploaded by

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

Express.js: Node.js Web Framework Guide

Uploaded by

Tejas Kadam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXPRESS.

JS
[Link] web application framework
Introduction
• If you write serious apps using only core [Link] modules you most likely find
yourself reinventing the wheel by writing the same code continually for similar
tasks, such as the following:
 Parsing of HTTP request bodies and Parsing of cookies
 Managing sessions
 Organizing routes with a chain of if conditions based on URL paths and HTTP methods of
the requests
 Determining proper response headers based on data types

• Express is a web application framework for Node


 Its built on top of [Link].
 It provides various features that make web application development fast and easy
compared to [Link].
[Link] Installation
• Create a new folder: eg E:\Express-app
• E:\Express-app>npm init //for creating [Link]
• E:\Express-app>npm install express --save

{
"name": "express-app",
"version": "1.0.0",
"description": "",
"main": "[Link]",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
First app
• An Express app is created by calling the express() function
 express() : Creates an Express application; is a top-level function exported by the
express module
 The app object conventionally denotes the Express application.
 This object, which is traditionally named app, has methods for routing HTTP requests,
configuring middleware, rendering HTML views, registering a template engine, and
modifying application settings that control how the application behaves

let express = require("express") // import the express module

let app = express() // create an Express application

[Link]("/",function(req,resp){
[Link]("Hello world")
})

[Link](3000, function(){
[Link]("app running on port 3000")
})

The [Link]() method returns an [Link] object


Express Routes
• HTTP verb and URL combinations are referred to as routes, and Express has
efficient syntax for handling them.
Open browser and type:
var express = require("express"); [Link]
var http = require("http"); [Link]
var app = express(); [Link]
[Link] - gives error
[Link]("/", function(req, res, next) {
[Link]("Hello <strong>home page</strong>");
});

[Link]("/foo", function(req, res, next) {


[Link]("Hello <strong>foo</strong>");
});

[Link]("/bar", function(req, res, next) {


[Link]("Hello <strong>bar</strong>");
});
//app is passed to the [Link]() method

[Link](app).listen(8000);
Express Routes
• If none of your routes match the request, you'll get a "Cannot GET <your-
request-route>" message as response.

• This message can be replaced by a 404 not found page using this simple route

[Link]('*', function(req, res){


[Link]('Sorry, this is an invalid URL.');
});

[Link](‘/course/:id', function(req, res){


var course = //code to retrieve course
If(!course){
[Link](404).send(“course not found”);
});
Routing basics
[Link]("/", function(req, res, next) {
[Link]("Hello <strong>home page</strong>");
});

• The get() method defines routes for handling GET requests.


• Express also defines similar methods for the other HTTP verbs (put(), post(),
delete(), and so on).
 [Link](path, handler) : This METHOD can be applied to any one of the HTTP
verbs – get, post, put, delete.
 All methods take a URL path and a sequence of middleware as arguments.
 The path is a string or regular expression representing the URL that the route
responds to. Note that the query string is not considered part of the route’s URL.
• Also notice that we haven’t defined a 404 route, as this is the default behavior
of Express when a request does not match any defined routes.
Routing basics
[Link]("/", function(req, res, next) {
[Link]("Hello <strong>home page</strong>");
});

• Express also augments the request and response objects with additional
methods. Example [Link]() .
 send() is used to send a response status code and/or body back to the client.
 If the first argument to send() is a number, then it is treated as the status code. If a
status code is not provided, Express will send back a 200.
 The response body can be specified in the first or second argument, and can be a string,
Buffer, array, or object.

• send() also sets the Content-Type header unless you do so explicitly.


 If the body is a string, Express will set the Content-Type header to text/html.
 If the body is an array or object, then Express will send back JSON.
 If the response body is a Buffer, the Content-Type header is also set to application/octet-
stream
Routing basics
var express = require("express");
var app = express();
var path = require('path');

[Link]("/buff", function(req, res, next) {


var buff = [Link]("Hello World");
[Link]([Link]());
});
[Link]("/string", function(req, res, next) {
[Link]("Hello <strong>String response</strong>");
});
[Link]("/json", function(req, res, next) {
[Link]({name:'Soha',age:23});
});
[Link]("/array", function(req, res, next) {
[Link](['NodeJS','Angular','ExpressJS']);
});
[Link]("/file", function(req, res, next) {
[Link]([Link](__dirname + '/[Link]'));
});
[Link](3000);
Route Parameters
• Route can be parameterized using a regular expression

var express = require("express");


var http = require("http");
Ignore multiple slash
var app = express();
[Link](/\/products\/([^\/]+)\/?$/, function(req, res, next) {
[Link]("Requested " + [Link][0]);
});
[Link](app).listen(8000);

/products?productId=sweater
/products/sweater

The above regular expression matches anything but /


/products/books
/products/books:aaa
/products/books/
/products/books?aaa
/products/books=aaa

Doesn’t match:
/products/books/aaa
/products/books//
/products//
Eg 2 : Using regular expressions to match routes
 Assume you want to match things like /users/123 or /users/456 but not /users/anita. You
can code this into a regular expression and also grab the number

[Link](/^\/users\/(\d+)$/, function(req, res) {


var userId = parseInt([Link][0], 10);
[Link]("Requested " + userId);
});

• [Link] - An object containing parameter values parsed from the URL path.
 For example, if you have the route /user/:name, then the “name” property is available
as [Link]. This object defaults to {}.
 GET /user/shrilata
 [Link] // => “shrilata“

 When you use a regular expression for the route definition, each capture group match
from the regex is available as [Link][0], [Link][1]
 GET /file/javascripts/[Link]
 [Link][0] // => "javascripts/[Link]"
Route Parameters
• One of the most powerful features of routing is the ability to use placeholders to
extract named values from the requested route, marked by the colon ( :)
character.
 When the route is parsed, express puts the matched placeholders on the [Link]
object for you.

[Link]('/user/:id', function(req, res) { Placeholders match any


[Link]('user ' + [Link]); sequence of characters except for
}); forward slashes.

[Link](‘/product/:prodname', function(req, res) {


[Link](‘Product : ' + [Link]);
});
Route Parameters
 Below example, creates a named parameter productId.

[Link]("/product/:productId(\\d+)", function(req, res, next) {


[Link]("Requested " + [Link] );
});

productId can now only be made up of digits


Invoke as : [Link]

[Link]('/users/:userId/books/:bookId', function (req, res) {


[Link]([Link])
//[Link]([Link] + ":" + [Link])
})
//Route path: /users/:userId/books/:bookId
//Request URL: [Link]
//[Link]: { "userId": "34", "bookId": "8989" }
Working with parameters using get
• [Link]
 Express parses query string parameters by default, and puts them into the [Link]
property.
 If the request is GET /search?username=Shrilata
[Link] returns “Shrilata"

 Lets say the incoming url is : [Link]


 Use [Link] to query the request parameters

[Link]("/add", function (req, res) {


n1 = parseInt([Link].no1);
n2 = parseInt([Link].no2);
[Link]("Addition : " + (n1 + n2) );
});
Handle GET Request
Multiple different methods
• We can also have multiple different methods at the same route.

var express = require('express');


var app = express();

[Link]('/hello', function(req, res){


[Link]("Hello World!");
});

[Link]('/hello', function(req, res){


[Link]("You just called the post method at '/hello'!\n");
});

[Link]('/hello', function(req, res){


[Link]("You just called the delete method at '/hello'!\n");
});

[Link](3000);
Handle POST Request
• To handle HTTP POST request in [Link] version 4 and above, you need
to install a middleware module called body-parser.
 This is used to parse the body of requests which have payloads attached to them.

 Install it using : npm install --save body-parser


 Mount it by including the following lines in your js

var bodyParser = require("body-parser");


[Link]([Link]({ extended: false }));

 This body-parser module parses the JSON, buffer, string and url encoded data
submitted using HTTP POST request.
 Eg :To parse json data: [Link]([Link]())

[Link](): Parses the text as URL encoded data (which is how


browsers tend to send form data from regular forms set to POST) and exposes the
resulting object (containing the keys and values) on [Link]
Handle POST Request
Routing handlers
• [Link](path, callback [, callback ...])
 Routes HTTP GET requests to the specified path with the specified callback
functions. Callback functions can be:
o A middleware function.
o A series of middleware functions (separated by commas).
o An array of middleware functions.

 The next() function gives you the opportunity to do some additional examinations on
the incoming URL and still choose to ignore it

[Link]('/example/b', f1 , f2 , f3);

……..
function f1(){
//handle the callback
next();
}
Routing handlers
//More than one callback function can handle a route
[Link]('/example/b', function (req, res, next) {
[Link]('the response will be sent by the next function ...')
next()
}, function (req, res) {
[Link]('Hello from B!')
})

//An array of callback functions can handle a route.


var cb0 = function (req, res, next) {
[Link]('CB0')
next()
}

var cb1 = function (req, res, next) {


[Link]('CB1')
next()
}

var cb2 = function (req, res) {


[Link]('Hello from C!')
}
[Link]('/example/c', [cb0, cb1, cb2])
Views, templates, template engines
• A template engine facilitates you to use static template files in your applications.
 At runtime, it replaces variables in a template file with actual values, and transforms the
template into an HTML file sent to the client.
 This approach makes it easier to design an HTML page.
 Some popular template engines that work with Express are Pug, Mustache, Haml,
Hogan, Swig and EJS.

• Using EJS:
1. install ejs : npm install ejs –save
2. Create a folder called “views” in main project folder
Views, templates, template engines
• Create a file called [Link] and put it into the “views” directory

You might also like