More Related Content Similar to Build web application by express Similar to Build web application by express (20) Build web application by express1. express Web
weibo.com/mengxy
www.imeigu.com
8. Express
• Express by TJ Holowaychuk is an extremely
popular web framework. It’s fast, simple, and
easy to learn, and even better — it’s actively
maintained
——Alex Young from dailyjs.com
9. demo
• git clone https://github.com/visionmedia/
express.git
• npm install express
• node bin/express /tmp/foo && cd /tmp/foo
• npm install -d
10. var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'your secret
here' }));
app.use(app.router);
});
app.get('/', function(req, res){
res.render('Hello world');
});
app.listen(3000);
11. Routes
function loadUser(req, res, next) {
var user = users[req.params.id];
if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user ' +
req.params.id));
}
}
app.get('/user/:id', loadUser, function(req, res){
res.send('Viewing user ' + req.user.name);
});
12. Cookie & Session
function loadUser(req, res, next) {
if (req.session.user) {
return req.session.user;
}
var user = users[req.params.id];
if (user) {
req.session.user = req.user = user;
next();
} else {
next(new Error('Failed to load user ' +
req.params.id));
}
}
15. var request = require('request');
request(
{uri:'http://www.google.com'},
function (error, response, body) {
if (!error && response.statusCode == 200) {
sys.puts(body) // Print the google web
page.
}
})
18. Stache
• Stache is mustache.js for your node
express apps
app.set('view engine', 'mustache')
app.register(".mustache", require('stache'));
19. app.get('/', function (req, res) {
res.render("index", {
locals: {
title: "Title content",
body: "Page content"
},
partials: {
heading: '<title>{{title}}</title>'
}
});
});
<!-- index.mustache -->
<html>
<head> {{>heading}} </head>
<body> {{{body}}} </body>
</html>
20. app.get('/', function (req, res) {
res.render("index", {
locals: {
title: "Title content",
body: "Page content"
},
partials: {
heading: '<title>{{title}}</title>'
}
});
}); <html>
<head>
<!-- index.mustache --> <title>Title content</title>
<html> </head>
<head> {{>heading}} </head> <body> Page content </body>
<body> {{{body}}} </body> </html>
</html>
26. node
node
1. try{…} catch(error){…}
27. node
node
1. try{…} catch(error){…}
2. process.on('uncaughtException', function
(err) {//doSomething}
30. app.get("/err", function(req, res, next){
fs.readFile('file', function(err, data){
if (err) {next(err);}
});
})
app.error(function(err, req, res){
console.err(err.stack);
res.render("500.html", {
locals: {
page_title: '500_ _i '
},
status: 500
});
});
31. express tips
• try{}catch(e){}
• routes callback error throw
error next() express
• uncaughtException node
endless world