Upload
gergely-nemeth
View
1.838
Download
3
Embed Size (px)
DESCRIPTION
Express: web application framework for node Includes: getting started (install), configuration, middlewares, session management, routing and rendering
Citation preview
Node.js with Expressweb application framework for node
Gergely Nemeth
What is Express?
get '/' do redirect to('/hello/World')end get '/hello/:name' do "Hello #{params[:name]}!"end
Gergely Nemeth
● Node.js web framework
● Sinatra-inspired
Getting started
Gergely Nemeth
● npm install express
var express = require('express');
var app = express();
app.get('/hello', function(req, res){
res.send('Hello World');
});
app.listen(3000);
console.log('Listening on port 3000');
Getting started #2
Gergely Nemeth
● npm install -g express
● express --sessions --css stylus --ejs myapp
● create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.styl
create : myapp/routes
create : myapp/routes/index.js
create : myapp/views
create : myapp/views/index.ejs
Configuration
Gergely Nemeth
Used to separate production/development/etc... configurations (based on NODE_ENV)
// all environmentsapp.configure(function(){ app.set('title', 'Rescue');})
// development onlyapp.configure('development', function(){ app.set('mongoUrl', 'localhost/dev');})
// production onlyapp.configure('production', function(){ app.set('mongoUrl', 'n.n.n.n/prod');})
Middlewares
Gergely Nemeth
● logging, auth, gzip, csrf protection, session management, etc...
● called sequentially, next() callback can trigger the next middleware
//built-in middlewaresapp.use(express.logger());app.use(express.compress());app.use(express.methodOverride());app.use(express.bodyParser());
//custom error handlingapp.use(function onError(err, req, res, next) { //do something with the error next(err);});
Routing
Gergely Nemeth
app.VERB(path, [callback...], callback)
● GET, POST, PUT, DELETE, PATCH● [callback...] are middlewares
app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){
var from = req.params[0];
var to = req.params[1] || 'HEAD';
res.send('commit range ' + from + '..' + to);
});
Sessions
Gergely Nemeth
● With middlewaresapp.use(express.cookieParser()); app.use(express.cookieParser('some secret'));
● For authentication use:○ Passportjs○ Everyauth
Rendering
Gergely Nemeth
● With template engines: Mustache(hogan), Jade, EJS...
● Layout, views, partials● Variables are passed to the render engine
app.get('/', function(req, res) { res.locals = { title: 'Title', }; return res.render( 'index', { partials: { part: 'part', } } );});
Rendering #2
Gergely Nemeth
● part.html<h1>{{ title }}</h1>
● index.html{{> part}} Hello world!