Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Module 4 Oe

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 58

WEB TECHNOLOGIES

Presentation Material

Department of Computer Science & Engineering

Course Code: Semester: VII

Course Title: WEB TECHNOLOGIES Year: IV

Faculty Name: DR.GOUSIA THAHNIYATH, PROF AMRUTHA

Department of Computer Science &


Course Name & Course Code 1
Engineering
Introducing Express: Basics of Express, Express JS Middleware: Serving Static Pages ,Listing Directory Contents,
Accepting JSON Requests and HTML Form Inputs, Handling Cookies.
Express.JS
Basics of Express
*Express.JS
•Express.js (Express) is a light web framework which sits on top of
Node.js and it adds functionality like (middleware, routing, etc.) and
simplicity to Node.js.
•When creating a Node.js web application, we write a single JavaScript
application which listens to requests from the browser, based on the
request, the function will send back some data or an HTML web page.

Node.js APIs can get complex and writing how to handle a single request can end up
being over 50 lines of code. Express makes it easier to write Node.js web applications.
Advantages of using Express with Node.js

● 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.

npm install -g express

The following command will install latest version of express.js local to your
project folder.

C:\MyNodeJSApp> npm install express --save


Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your
working directory.

$ 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:

$ npm install express

To install Express temporarily and not add it to the dependencies list:

$ npm install express --no-save


The simplest Express application

var express = require('express'),


http = require('http');
// Create an express application
var app = express()
// register a middleware
.use(function (req, res, next) { res.end('hello express!'); });
// Register with http
http.createServer(app) .listen(3000);

//Having the ability to be registered as a listener with HTTP allows you to


use HTTPS if you want to (the same as Connect). Similar to Connect,
Express provides a utility listen function to register itself with http.
The simplest Express application can be as
simple as
var express = require('express');
express()
.use(function (req, res, next)
{ res.end('hello express!'); }) .listen(3000);

Also error handling works the same as Connect,


with an error handling middleware that takes four
arguments.
Create an app that starts a server using express.js that listenes on port 3000 .The app responds
with “Hello World!” for requests to the root URL (/) or route.

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)

Middleware is a set of functions that sit between a raw request and


the final intended route. Middleware functions have access to all the
HTTP requests coming to the server. Middleware can handle tasks
such as logging, sending static files, authorization, and session
management, etc.
In Express the request and response objects are passed through a set
of functions, called the middleware stack.
Every function in the stack takes three arguments request, response and next. next
is a function, that when called Express executes the next function in the stack. This
is a subtle difference between middleware and a route handler which we saw
above.
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 function 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

Middleware can handle tasks such as logging, sending static files, authorization, and session
management, etc.

Advantages

1. Optimization and better performance

2. Can manipulate request object before reaching the server

3. Can perform various functions on the request object

4. Can improve client-side rendering performance

5. Setting some specific HTTP headers


Types of express middleware

● Application level middleware app.use

● Router level middleware router.use

● Built-in middleware express.static,express.json,express.urlencoded

● Error handling middleware app.use(err,req,res,next)

● Thirdparty middleware bodyparser,cookieparser


built-in middleware
Starting with version 4.x, Express no longer depends on Connect. The middleware functions that were previously included with Express
are now in separate modules; see the list of middleware functions.

Express has the following built-in middleware functions:

● 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

next middleware function is commonly denoted by a variable named next.


1. As name suggests it comes in middle of something and that is request and response

cycle

2. Middleware has access to request and response object

3. Middleware has access to next function of request-response life cycle


What is this next()?

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

Serving Static Pages One of the most common


things you will want to right away is serve static
web-site content. The serve-static middleware
(npm install serve-static) is designed specifically
for that.
static file server to understand middleware

There are two option

first : fs.stat(filePath, function(err, fileInfo)

Second: app =Express()

app.use(express.static(public DirectoryPath))

/
static/1 basic.js

var express = require('express');


var serveStatic = require('serve-static');
var app = express()
.use(serveStatic(__dirname +
'/public')) .listen(3000);
● Run this code using node and

● you get a simple web server serving web


pages from the `/public` directory.

This little server does quite a few nice things


including the following:(see next slide )
Sets the proper mime type of the response

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)

Serves the index.html from a directory if the path resolves to a directory


Note
By using use ‘__dirname’, we make sure that the path is
always relative to the current file instead of the current
working directory (CWD).
The CWD may be different from the file directory if we
run our application from another directory such as from
one level up using ‘node static/1basic.js’ instead of the
same directory—that is, ‘node 1basic.js’. Relative path
names such as ‘./public’ resolve relative to the CWD.
Using ‘__dirname’, making it independent of the CWD.
Express ships with the static middleware as a
part of its NPM package.
So if you are using Express, you can use
express.static, which is an alias to require('serve-
static').

Next slide shows how the example can be


rewritten.
static/2 static.js

var express = require('express');


var app =
express() .use(express.static(__dirname +
'/public')) .listen(3000);
Initialize a new npm project. Then create a directory named static and copy-paste any available static files into
the folder (text, images, etc.).

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();

app.use(function(req, res, next) {


console.log("Request IP: " + req.url);
console.log("Request date: " + new Date());
next();
});

app.use(function(req, res, next) {


var filePath = path.join(__dirname, "static", req.url);
fs.stat(filePath, function(err, fileInfo) {
if (err) {
next();
return;
}
if (fileInfo.isFile()) {
res.sendFile(filePath);
} else {
next();
}
});
});
app.listen(3000, function() {
console.log("App started on port 3000");
});
If we run this file using node app.js and go to localhost:3000/dummy_file.txt, we can see on the screen
file1.
If we go to the URL localhost:3000, we see an error Cannot GET / because we did not configure a route
handler for that path.
Request & Response

• Express application uses a callback function whose parameters


are request and response objects
app.get('/', function (req, res) {
// -- })
Request Object − The request object represents the HTTP request and has
properties for the request query string, parameters, body, HTTP headers, and so on.
Response Object − The response object represents the HTTP response that an
Express app sends when it gets an HTTP request.
Program 2: to understand request received to server
using get method
First.js :
const exp=require("express");
const app=exp();
app.get("/",function(req,res){
res.send("Welcome to express");
});
app.get("/index",function(req,res){
res.send("Home page")
});
app.get("/aboutus",function(req,res){
res.send("about us page")
});
app.get('*',(req,res)=>{
res.send("Requested Page could not be found");
});
app.listen(7777);
Output:

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

Body parsing is the act of parsing a string based


client request body into a JavaScript object that
you can easily consume in your application code.

This is a very common task in web development,


making the body-parser middleware (npm install
body-parser) a must-have in your toolbelt.
Parses the request body into a JavaScript object
if the content-type matches JSON
(application/JSON) or a user submitted HTML
form (the browser sends it as the MIME type
application/x-www-form-urlencoded)

Puts this JavaScript object (if the parse was


successful) in req.body for easy access in later
middleware
Requesting JSON Content

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); }

else { res.end('Body does not have foo!'); } })


.use(function (err, req, res, next) { res.end('Invalid
body!'); }) .listen(3000);
The body-parser sets the req.body to an empty
object if the request body does not contain any
JSON or urlencoded payload. However, if an
invalid JSON content is sent by the client, it
raises an Express error, which you can handle
with an error handling middleware
Testing bodyparser/basic.js with JSON Content

$ curl http://127.0.0.1:3000/ -H "content-type:


application/json" -d "{\"foo\":123}"
Body parsed! Value of foo: 123
$ curl http://127.0.0.1:3000/ -H "content-type:
application/json" -d "{\"foo\":123,}"
Invalid body!
The body-parser middleware allows us to use
the same code if the client sends an HTML form
data (instead of JSON), as shown
Testing bodyparser/basic.js with HTML Form
Content
$ curl http://127.0.0.1:3000/ --data-urlencode
"foo=123" Body parsed! Value of foo: 123
Body Parser
Second way: Accepting from a form
to use bodyParser()
Accepting JSON req and HTML form Inputs

//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)

var bodyParser = require('body-parser')


app.use( bodyParser.json() ); // to support JSON-encoded

app.use(bodyParser.urlencoded({ // to support URL-encoded


extended: true
}));
Program-3 part 1(to understand request received
from client using post method-(hint):use (body-
parser)
//Index.html part 2

<!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

app.get('/aboutus', (req, res) => {


console.log("hi about us is here"+__dirname);
res.sendFile(__dirname+"/public/aboutus.html");
})
app.get('/demo', (req, res) => {
res.send("Demo on Static pages");
})
app.listen(3000, () => {
console.log('Server is up on port 3000.')
Index.html :
<!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>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<p>Acessing Static files like images,video and audio</p>
</body>
</html>
In css folder,create styles.css
Styles.css:
-----------
p{
Color:red;
}
//program to give parameters from browser
express=require('express');
app=express();expressexpr
app.get("/:a/:b",function(req,res) {
a=parseInt(req.params.a);
b=parseInt(req.params.b);
let c=a+b;

// 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.

You might also like