node.js express
DESCRIPTION
Node.js ExpressTRANSCRIPT
Eyal VardiMicrosoft MVP ASP.NET
blog: eyalvardi.wordpress.com
Express Web Application Framework for Node.js
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Agenda
Why Express.js?
Middleware
Routing
Configuration
Views & Templates
Session
Security
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Why Express.js ? Providing a robust set of features for
building web app’s. Configuration Routing
Middleware Views &
Templates
Session Securit
y
Without Express
// Require what we needvar http = require("http");
// Build the servervar app = http.createServer(
function (request, response) {response.writeHead(200, {
"Content-Type": "text/plain" }); response.end("Hello world!"); });
// Start that serverapp.listen(1337, "localhost");console.log("Server running at http://localhost:1337/");
Pipe Code
How to Route Without Expressvar http = require("http");http.createServer(function (req, res) {
// Homepage if (req.url == "/") { res.writeHead(200, { "Content-Type": "text/html" }); res.end("Welcome to the homepage!"); }// About page else if (req.url == "/about") { res.writeHead(200, { "Content-Type": "text/html" }); res.end("Welcome to the about page!"); } // 404'd! else { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 error! File not found."); }
}).listen(1337, "localhost");
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
What is middleware? Middleware is a request handler.
Routing , Controller, Models, Views… Security
function myFunMiddleware(request, response, next) { // Do stuff with the request and response. // When we're all done, call next() to defer // to the next middleware. next();}
Middleware
Middleware
Middleware
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Connect Use Method A middleware framework for node.var connect = require("connect");var http = require("http");var app = connect();
http.createServer(app).listen(1337);
// Add some middlewareapp.use(function (request, response) { response.writeHead(200, { "Content-Type": "text/plain" response.end("Hello world!\n");});
// Add some middleware app.use(connect.logger()); app.use(connect.Security); app.use(connect.Routing); ...
Express Routing
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Express Routingvar express = require("express");var http = require("http");var app = express();
app.all("*", function (request, response, next) { response.writeHead(200, { "Content-Type": "text/plain" }); next(); });
app.get("/", function (request, response) { response.end("Welcome to the homepage!"); });
app.get("/about", function (request, response) { response.end("Welcome to the about page!"); });
app.get("*", function (request, response) { response.end("404!"); });
http.createServer(app).listen(1337);
Express Routingapp.get('/users/:id?', function (req, res, next) { var id = req.params.id; if (id) { // do something } else { next(); }});
{ path: '/user/:id?', method: 'all' | 'get' | 'post' | 'put' | 'delete', callbacks: [ [Function] ], keys: [ { name: 'id', optional: true } ], regexp: /^\/user(?:\/([^\/]+?))?\/?$/i, params: [ id: '12' ] }
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Routing and Module// home.js file in Routing folder.module.exports = function (app) { // home page app.get('/', function (req, res) { res.render('index', { title: 'Home Page. ' }) }); // about page app.get('/about', function (req, res) { res.render('about', { title: 'About Me. ' }) });}
var express = require("express");var http = require("http");var app = express();
// Include a route file require('./routes/home')(app);
http.createServer(app).listen(1337);
Routing
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Routing Templates One to one
One to many
app.get('/users/:id?', function (req, res, next) { ... }
'/:controller/:action/:id'
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Configuration Conditionally invoke callback when env
matches app.get('env'), aka process.env.NODE_ENV.// all environmentsapp.configure(function() { app.set('title', 'My Application');});
// development onlyapp.configure('development', function() { app.set('db uri', 'localhost/dev');});
// production onlyapp.configure('production', function() { app.set('db uri', 'n.n.n.n/prod');});
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Express Setting Supports the following settings out of the
box: basepath views view engine view cache case sensitive routes strict routing jsonp callback
Http Methods
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
HTTP Methods app.get(), app.post(), app.put() &
app.delete()
By default Express does not know what to do with this request body, so we should add the bodyParser middleware.
bodyParser will parse application/x-www-form-urlencoded and application/json request bodies and place the variables in req.bodyapp.use( express.bodyParser() );
PUT Samples
app.put('/', function(){ console.log(req.body.user); res.redirect('back');});
<form method="post" action="/"> <input type="hidden" name="_method" value="put" /> <input type="text" name="user[name]" /> <input type="text" name="user[email]" /> <input type="submit" value="Submit" /> </form>
app.use(express.bodyParser());app.use(express.methodOverride());
Use POST,but the node see it as PUT
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
Error Handling Express provides the app.error() method
which receives exceptions thrown within a route, or passed to next(err).
function NotFound(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee);}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function (req, res) { throw new NotFound;});
app.get('/500', function (req, res) { throw new Error('keyboard cat!');});
app.error(function (err, req, res, next) { if (err instanceof NotFound) { res.render('404.jade'); } else { next(err); }});
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
errorHandler Middleware Typically defined very last, below any
other app.use() calls.
app.use(express.bodyParser());app.use(express.methodOverride());app.use(app.router);app.use(function(err, req, res, next){ // logic}); app.use(express.bodyParser());
app.use(express.methodOverride());app.use(app.router);app.use(logErrors);app.use(clientErrorHandler);app.use(errorHandler);
Views
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
View Template Engines Express support many template engines:
Haml Jade EJS
// Start Expressvar express = require("express");var app = express();
// Set the view directory to /viewsapp.set("views", __dirname + "/views");
// Let's use the Jade templating languageapp.set("view engine", "jade");
CoffeeKup jQuery Templates
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
View Rendering View filenames take the form
“<name>.<engine>”, where <engine> is the name of the module that will be required.
app.get('/', function (req, res) { res.render( 'index.jade', { title: 'My Site' } );});
View file
Model
© 2014 All rights reserved. Tel: 054-5-767-300, Email: [email protected]
View Layout & Partials The Express view system has built-in
support for partials and collections, which are “mini” views representing a document fragment.
res.render('page', { layout: 'mylayout.jade' });
partial('header', headerData );Partial View
Partial View
View
Layout
partial('footer', footerData );
Views
Thankseyalvardi.wordpress.com
Eyal VardiMicrosoft MVP ASP.NETblog: eyalvardi.wordpress.com