Express 版本:4.13.1
1 啟動(dòng)服務(wù)
1.1 手動(dòng)啟動(dòng)
如果需要手動(dòng)啟動(dòng)服務(wù),執(zhí)行命令:
npm start
或:
DEBUG=LearnNodejs:* npm start
1.2 Supervisor自動(dòng)監(jiān)測(cè)文件變化
Superviosr 安裝資料 https://github.com/petruisfan/node-supervisor
全局安裝
npm install supervisor -g
安裝完畢后,執(zhí)行命令:
supervisor bin/www
supervisor 默認(rèn)監(jiān)測(cè)的是當(dāng)前目錄下的所有文件。當(dāng)項(xiàng)目文件夾中有文件變化時(shí),會(huì)重新執(zhí)行 bin/www文件;
為何不是supervisor app.js?
打開package.json
"scripts": {
"start": "node ./bin/www"
}
可以發(fā)現(xiàn)新版的express入口文件是bin/www而不是app.js
所以Supervisor 應(yīng)該指向bin/www,既當(dāng)文件發(fā)生改變的時(shí)候執(zhí)行node bing/www
2 初識(shí)視圖與路由:
2.1 添加視圖:
在./views/創(chuàng)建:about.jad
輸入代碼
extends layout
block content
h1= title
p this is #{title}
2.2 添加路由
在路由文件夾:./routes/添加about.js作為新的路由模塊,
輸入代碼
var express = require('express');
var router = express.Router();
/* GET about */
router.get('/',function(req,res,next){
//引用剛剛創(chuàng)建的視圖:./views/about.jad文件
res.render('about',{title:'About'});
});
module.exports = router;
在app.js加入以下代碼
//引入about路由模塊
var about = require('./routes/about');
//當(dāng)用戶訪問localhost:3000/about/路徑時(shí) 使用about模塊
app.use('/about',about);
如果是需要制定更深層的路徑,例如: /about/me該怎么做?
打開routes/about.js文件,添加以下代碼
/* GET about/me */
router.get('/me',function(req,res,next){
res.render('about',{title:'me'});
});
我們可以看出,在`routes/about.js`作為一個(gè)子模塊(sub-app)加載到app.js中。
3 更換模板引擎
Express 默認(rèn)的模板引擎為jad,如果要使用underscore.js模板怎么辦?
3.1 安裝underscore-express
npm install underscore-express
在app.js中引入underscore-express:
// view engine setup
app.set('views', path.join(__dirname, 'views'));
//設(shè)置模板文件格式`tmpl`
app.set('view engine', 'tmpl');
//引入underscore-express
require('underscore-express')(app);
3.2 創(chuàng)建undercore模板:
在views文件夾中創(chuàng)建header.tmpl
<html>
<head>
<title>Header!</title>
</head>
<body>
創(chuàng)建footer.tmpl
</body>
</html>
創(chuàng)建 index.tmpl
<%= include('header') %>
Welcome to <%= title %> !
<%= include('footer') %>
訪問 http://localhost:3000/
可以看到
Welcome to underscore !
4 RESTful API
Router 支持 RESTful 風(fēng)格的API:
先準(zhǔn)備好RESTful 調(diào)試工具,
Postman:
https://chrome.google.com/webstore/search/postman?utm_source=chrome-ntp-icon
然后就可以開始干了。
打開about.js 在
/* GET about */
router.get('/',function(req,res,next){
res.render('about',{title:'About'});
});
之后添加以下代碼:
/* POST about */
router.post('/',function(req, res, next){
res.json({method:'post', message:'ok',request:req.body});
});
上面代碼意思是, 當(dāng)用戶以POST方法傳遞數(shù)據(jù)進(jìn)來時(shí),我們將返回Json數(shù)據(jù)。req.body是指的是請(qǐng)求時(shí)傳遞過來數(shù)據(jù)。
如何調(diào)試呢?
可以照如下圖設(shè)置Postman:
- 地址:http://localhost:3000/about
- 格式:x-www-form-urlencoded
- 方法: PUT

點(diǎn)擊 Send 按鈕后,可以獲得響應(yīng):

Put,Delete方法也類似,代碼如下:
/* PUT about */
router.put('/',function(req,res,next){
res.json({method:'put', message:'ok',request:req.body});
});
/* DELETE about */
router.delete('/',function(req,res,next){
res.json({method:'delete', message:'ok',request:req.body});
});