Express is a web framework for Node.js that allows routing, middleware, templating and more. It is inspired by Sinatra and uses Connect as its middleware framework. Key features include routing, middleware support, template rendering with engines like Jade, and session handling with storage options. Errors can be handled via the app.error() method. Express provides a full-featured and easy to use web development framework for Node.js.
4. Routing
app.get('/users/:id?', function(req, res) {
var id = req.params.id;
res.send(id ? 'user ' + id : 'users');
});
app.post('/users/:id.:format', function(req, res) {
var id = req.params.id;
var format = req.params.format;
res.send('user: ' + id + ' format: ' + format);
});
app.get('/file/*.*', function(req, res) {
res.send('path: ' + req.params);
});
5. Connect / Middlewares
⢠Connect is a middleware framework
⢠Similar to Rack
⢠A middleware is simply a function with
three arguments: request, response, next
var helloWorld = function(req, res, next) {
res.writeHead(200, { 'Content-Type':
'text/plain' });
res.end('hello world');
}
6. Middleware
var loadUser = function(req, res, next) {
var id = req.params.id;
var user = db.loadUser(id); // fetch user from db
if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user ' + id));
}
}
app.get('/user/:id', loadUser, function(req, res) {
res.send('Viewing user ' + req.user.name);
});
7. HTTP POST
<form method="post" action="/">
<input type="text" name="user[name]" />
<input type="submit" value="Submit" />
</form>
bodyDecoder middleware for POST params:
app.use(express.bodyDecoder());
app.post('/', function(req, res){
console.log(req.body.user);
res.redirect('back');
});
9. View Rendering
⢠Concept: Layout, view and partials
⢠Template Engines: Jade, Haml, EJS, âŚ
⢠View variables are passed to render
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.haml', {
layout: 'app', // -> app.jade
locals: { title: 'This is my app' }
});
});
10. Jade - Template Engine
!!!
html(lang="en")
head
title= pageTitle
:javascript
| if (foo)
|
bar()
body
h1 Jade - node template engine
#container
- if (youAreUsingJade)
p You are amazing
- else
p Get on it!
.comments
= partial('comment', comments)