Request Handling, Routing, Views and Middlewares
Chandan Jhunjhunwal
Session -2
03/02/2017
Why Express
- Middleware
- Routing
- Extension to Req/Res objects
- Views
Why Express
- Middleware
- Routing
- Extension to Req/Res objects
- Views
Middleware
Typical NodeJS Req/Res cycle
Req/Res with Middleware
Middleware
Req/Res flow
Middleware
Req/Res flow
// Middleware function
function myMiddleWare(request, response, next){
...
next();
}
// A simple logger middleware
var express = require('express');
var app = express();
app.use(function(req, res, next){
console.log("Inside middleware" + req.url);
next();
});
app.use(function(req, res){
res.status(200).send('Hello world!')
});
app.listen(3000)
A simple middleware
// express static middleware
var express = require('express');
var path = require('path');
var app = express();
var publicPath = path.resolve(__dirname, 'public');
app.use(static(publicPath));
app.use(function(req, res, next){
console.log("Inside middleware" + req.url);
next();
});
app.use(function(req, res){
res.status(200).send('File not found!')
});
app.listen(3000)
Express Static middleware
Express Routing
app.get('/', function(req, res){
res.status(200).send("Homepage");
});
app.get('/about', function(req, res){
res.end("About Page");
})
app.get('/users/:username', function(req, res){
res.end("Hello ", req.params.username);
});
app.use(function(req, res){
res.status(404).send("404");
});
- Write an express app, which blocks requests from a given IP address.
Views
- View can be static or dynamic.
- Template engines are used for dynamic views
- EJS, Pug, Nunjucks, Jade etc
// app.js
var express = require("express");
var path = require("path");
var app = express();
app.set("views", path.resolve(__dirname, "views");
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("index", {
message: "Rendered index page";
};
});
// index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello All</title>
</head>
<body>
<%= message %>
</body>
</html>
GuestBook Using Express
Request Handling, Views and Middleware in ExpressJS
By Chandan Jhunjhunwal
Request Handling, Views and Middleware in ExpressJS
- 550