Module 4 Oe
Module 4 Oe
Module 4 Oe
Presentation Material
● Express lets you take away a lot of the complexities of Node.js while adding
helpful functions to a Node.js HTTP server.
● Instead of a large request handler function, Express allows us to handle requests
by writing many small modular and maintainable functions.
● Express is not opinionated, meaning Express does not enforce any “right way”
of doing things. You can use any compatible middleware, and you can structure
the app as you wish, making it flexible.
● We can integrate with a template rendering engine (also called a view rendering
engine in some articles) of our choice like Jade, Pug, EJS, etc.A template engine
enables you to use static template files and at runtime change the values of
variables in those files.
●You can set up “middleware” for request processing.
*Install Express.js
You can install express.js using npm. The following command will install latest
version of express.js globally on your machine so that every Node.js application on
your machine can use it.
The following command will install latest version of express.js local to your
project folder.
$ mkdir myapp
$ cd myapp
Use the npm init command to create a package.json file for your application. For more information on how
package.json works, see Specifics of npm’s package.json handling.
$ npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply
hit RETURN to accept the defaults for most of them, with the following exception:
entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the
suggested default file name.
Now install Express in the myapp directory and save it in the dependencies list. For example:
let’s write the code for our example app. Create a file called app.js.
1// in app.js
var express = require("express");
var app = express();
//2
app.get("/", function(req, res){
res.send("HELLO WORLD");
});
//3
app.listen(3000, function(){
console.log("Application started and Listening on port 3000");
});
Core parts of Express(Middleware)
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
Middleware can handle tasks such as logging, sending static files, authorization, and session
management, etc.
Advantages
● express.static serves static assets such as HTML files, images, and so on.
● express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+
● express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+
Third-party middleware
● Use third-party middleware to add functionality to Express apps.
● Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.
● The following illustrates installing and the cookie-parsing middleware function cookie-parser.
● $ npm install cookie-parser
How Node JS middleware Works?
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
cycle
A middleware is basically a function that will the receive the Request and Response objects, just
like your route Handlers do. As a third argument you have another function which you should
call once your middleware code completed. This means you can wait for asynchronous database
or network operations to finish before proceeding to the next step. This might look like the
following: 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
The serve-static middleware
app.use(express.static(public DirectoryPath))
/
static/1 basic.js
Has good HTTP response codes (For example, if you refresh the page and
the HTML hasn’t changed, you will notice that it sends the response 304
Not Modified, instead of 200 OK. If you request a file that doesn’t exist,
you get a 404. If the file cannot be accessed for some reason, it sends a
500 Internal Server Error response.)
By default, does not allow you to get files above the directory you want to
serve (not vulnerable to the ../path bug we had in our simple server from
the previous chapter)
Execute the following commands in the terminal. The touch command creates an empty file.
$ npm init –y
$ npm install express
$ mkdir static
$ touch static/dummy file.txt
$ touch static/dummy file2.txt
$ echo file1 > static/dummy_file.txt
$ echo file2 > static/dummy_file2.txt
$ touch app.js
/app.js Our app will have a logger function and a static file serving function.
var express = require("express");
var path = require("path");
var fs = require("fs");
var app = express();
Node first.js
Open browser. Type in the URL : localhost:7777/index
Output is “home page”
2. localhost:7777/contact
Output is : Requested Page could not be found
*(more)MIDDLE WARES IN EXPRESSS
- BODY PARSER
- COOKIE PARSER
- Serve-index
- -The serve-static middleware (explained in
earlier slides
Body parsing
First way:
bodyparser/basic.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express()
.use(bodyParser())
.use(function (req, res)
{ if (req.body.foo)
{
res.end('Body parsed! Value of foo: ' + req.body.foo); }
//You need to use bodyParser() if you want the form data to be available in
req.body.It is middleware.
It is middleware in order for us to be able to read the “body” of an incoming JSON
object. This piece of middleware was called body-parser
// tells the application to use body-parser as middleware so it can handle post
requests app.use (bodyParser.urlencoded({extended:true}));
How To Get Post A Query In Express.js? Retrieve the POST query parameters using Express
[The two following ways)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/" method="POST"> //or else action="http://127.0.0.1:port num/"
<label>Enter First no:</label><br>
<input type="number" name="num1" placeholder="Enter first no"><br>
<label>Enter First no:</label><br>
<input type="number" name="num2" placeholder="Enter second no"><br>
<input type="submit">
</form>
</body>
</html>
Program-3 part 1(to understand request received
from client using post method-(hint):use (body-
parser)
Calc.js
const express=require('express');
const bodyParser=require('body-parser');
const app=express();
app.use(bodyParser.urlencoded({extended:true}));
app.get("/",function(req,res)//CALLED BI-DAEFAULT ON REQUEST ROUTE IN BROWSER
{ res.sendFile(__dirname+"/index.html");
});
console.log(__dirname);
console.log(__filename);
app.post("/",function(req,res){ //CALLED ON SUBMISSION VIA POST FROM A FORM
console.log(req.body);
result=Number(req.body.num1)+Number(req.body.num2);
res.send("The result is "+ result);
})
app.listen(4433,function(){
console.log("Listening to port no 4433");
})
Program 4(next slide)
Steps:Create a static directory.
• Add app.js file and Create a directory public,add index.html file in public folder,
you can also create css folder and images folder in public directory.
Program 4: To serve static files
https://www.geeksforgeeks.org/express-js-express-static-function/
//App.js
const path = require('path')
const express = require('express')
const app = express()
console.log("Directory is ",__dirname);
console.log("filename is ",__filename);
const publicDirectoryPath = path.join(__dirname, '../public');
console.log(publicDirectoryPath);
//tells express where to find all the static files (HTML,CSS etc) and load them into the browser
// note the index file that is present in the public folder will be directly expected on ‘/’ in the browser by default
app.use(express.static(publicDirectoryPath))
//let aboutus.html be another program in the public folder.. then write the below handler
// res.status(200).send(String(c));
res.send(String(c));
});
app.listen(9124,function(){
console.log("Listening to port no 9124");
});
output
* TO SERVE COOKIES USING
EXPRESS
TO SERVE COOKIES USING EXPRESS
http://expressjs.com/en/resources/middleware/cookie-parser.html
Express Code : To print al the cookies sent by the client using express
var express =require (‘express‘)
var cookieParser =require(‚cookie-parser‘)
var app=express()
app.use(cookieParser())
app.get( ‘/‘,function(req,res)
{
console.log(‘‘Cookies : “ , req.cookies)
})
app.listen(8081)
node cookie.js
Cookies: [Object: null prototype] {}
Signed Cookies: [Object: null prototype] {}
LISTING DIRECTORY CONTENTS
To list the contents of a directory, there is the
serve-index (npm install serve-index)
middleware.
Since it only lists the contents of the directory, it
is conventional to use it in conjunction with the
servestatic middleware to actually allow the
user to get the file.
var express = require('express');
var serveIndex = require('serve-index');
var app =
express() .use(express.static(__dirname +
'/public')) .use(serveIndex(__dirname +
'/public')) .listen(3000);
Default directory listing by serve-index
middleware
Notice that we registered serve-static before
serve-index as it gives serve-static an
opportunity to serve an index file if there is one
instead of serve-index responding with a
directory listing.