build web application by express

34
使用express构建Web应用 孟祥宇:weibo.com/mengxy www.imeigu.com

Upload: shawn-meng

Post on 02-Dec-2014

2.348 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Build web application by express

使用express构建Web应用孟祥宇:weibo.com/mengxy

www.imeigu.com

Page 2: Build web application by express

我们的场景

•奉行价值投资理念的互联网金融信息服务公司• 股票的价格资料查询、研究分析和新闻报道• 给投资者提供最好的互动交流体验

Page 3: Build web application by express

我们眼中的前后端• 后端工程师与机器打交道• 完善的 Web 服务接口

• 接口的响应速度• 可用性• 可扩展性• ……

Page 4: Build web application by express

我们眼中的前后端

• 前端工程师与用户打交道• 涉及到服务器的 Web 优化策略

• 根据需求来决定HTML的渲染位置

Page 5: Build web application by express
Page 6: Build web application by express

我们直接用node.js来开发Web应用吗?

Page 7: Build web application by express

Node的HTTP模块

• 没有内置的cookie parser

• 没有内置的session支持

• 没有内置的路由分发模块• 没有内置的模板系统

Page 8: Build web application by express

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

Page 9: Build web application by express

安装与创建demo

• git clone https://github.com/visionmedia/express.git

• npm install express

• node bin/express /tmp/foo && cd /tmp/foo

• npm install -d

Page 10: Build web application by express

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);

Page 11: Build web application by express

Routesfunction 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);});

Page 12: Build web application by express

Cookie & Sessionfunction 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)); }}

Page 13: Build web application by express

Do HTTP request

• 自己用node的http模块

• 社区里封装好的库

Page 15: Build web application by express

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. } })

Page 16: Build web application by express

Template Engines

• Haml

• Jade

• EJS

• CoffeeKup

• ……

Page 17: Build web application by express

Mustache

• Logic-less templates

• 在浏览器端使用很方便

• 浏览器和服务器共用模板

Page 18: Build web application by express

Stache

• Stache is mustache.js for your node express apps

app.set('view engine', 'mustache')app.register(".mustache", require('stache'));

Page 19: Build web application by express

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>

Page 20: Build web application by express

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>

<html><head> <title>Title content</title> </head><body> Page content </body></html>

Page 21: Build web application by express

然后呢?

Page 22: Build web application by express

然后呢?

BUG呗

Page 23: Build web application by express

然后呢?

BUG呗

我们的程序不可能保证万无一失,肯定有些没有处理的错误。这就让很多人觉得NodeJS不稳定,容易产生很多故障。

Page 24: Build web application by express

然后呢?

BUG呗

我们的程序不可能保证万无一失,肯定有些没有处理的错误。这就让很多人觉得NodeJS不稳定,容易产生很多故障。

但是我们要避免!

Page 25: Build web application by express

原因:只要程序中有错,node就会退出。解决方案:

node自己退出了

Page 26: Build web application by express

原因:只要程序中有错,node就会退出。解决方案:

1. 使用 try{…} catch(error){…} 来执行容易出错的代码段

node自己退出了

Page 27: Build web application by express

原因:只要程序中有错,node就会退出。解决方案:

1. 使用 try{…} catch(error){…} 来执行容易出错的代码段

2. process.on('uncaughtException', function (err) {//doSomething}

node自己退出了

Page 28: Build web application by express

访问没有响应app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ });})

if (err) {throw err;}

Page 29: Build web application by express

访问没有响应app.get("/err", function(req, res, next){ fs.readFile('file', function(err, data){ });})

if (err) {next(err);}

Page 30: Build web application by express

访问没有响应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 }); });

Page 31: Build web application by express

让express稳定的tips

• 容易出错的代码片段一定要try{}catch(e){}

• 在routes的callback里得到error时不能throw了之,记得把error用next()传递回express来做错误处理

• uncaughtException虽然可以让node进程活着,但是已经丢失上下文,你的用户进入了endless world

Page 32: Build web application by express

One more tool

Page 33: Build web application by express

Forever

• 确保脚本在持续运行着• Github: https://github.com/indexzero/

forever

• npm install forever

• forever start app.js

Page 34: Build web application by express

Thank You!

PS: We Are Hiring!

weibo.com/[email protected]