Express框架入門:初級篇
express 是nodejs的一個流行的web框架。本文主要介紹將express作為服務端對外提供API接口時,需要了解的入門知識。
1. Hello World
首先安裝node(如果已安裝,則略過):
$ brew install node
創建一個項目,然后安裝express:
$ mkdir express-hello-world && cd express-hello-world
$ npm init
$ npm install express --save
npm init 會提示輸入一些配置信息,回車使用默認值即可,執行完后,當前目錄下會自動創建 package.json 文件。
npm install express --save 表示為當前項目安裝express依賴,該依賴信息會保存在 package.json 文件中。
新建文件 index.js 文件, 輸入以下內容:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('hello, world!');
});
app.listen(3000);
運行:
$ node index.js
瀏覽器訪問: http://localhost:3000/ ,會輸出”hello, world!”。
2. 中間件middleware
在express中,中間件(middleware)函數是一種特殊的函數,它可以訪問一個http請求周期中的request對象、response對象,以及表示調用棧中的下一個中間件函數的引用,如:
function (req, res, next) {
next();
}
其中, req , res 和 next 三個參數名是約定的,不要使用其它的變量名。中間件函數可以修改request和response,或者提前結束response,也可以調用 next() 表示將執行傳遞給調用棧中的下一個中間件函數。
如果當前中間件函數沒有結束HTTP請求,則必須調用 next() 將執行傳遞給下一個中間件函數,否則請求會掛起。
使用 app.use() 加載中間件函數,中間件函數加載的順序決定了它的執行順序,即先加載,先執行。
在上面hello-world的例子中,我們增加兩個簡單的中間件函數,分別打印兩條日志信息。在 var app = express(); 的后面增加以下代碼:
app.use(function (req, res, next) {
console.log('in middleware one...');
next();
});
app.use(function (req, res, next) {
console.log('in middleware two...');
next();
});
執行后,終端會依次輸出兩個中間件函數中的日志信息。
express中的中間件可以分為以下幾類:
- app級中間件
- router級中間件
- 錯誤處理中間件
- 內置中間件
- 第三方中間件
這里僅簡要介紹一下主要的app級中間件和router級中間件。
app級中間件,即將中間件函數綁定到 app 對象(即使用 express() 得到的對象),通過 app.use() 或者 app.METHOD() 方法來加載中間件函數,其中 METHOD() 表示HTTP請求中的 GET/POST/PUT 等方法。上面的hello-world示例中就是app級中間件:
app.get('/', function(req, res) {
res.send('hello, world!');
});
router級中間件與app級中間件的用法基本一致,不同的是,它將中間件函數綁定到 express.Router() 對象,通過 router.use() 或者 router.METHOD() 方法來加載。比如上面的app級中間件,用router級中間件的方法改寫如下:
var router = express.Router();
router.get('/', function(req, res) {
res.send('hello, world!');
});
app.use('/', router);
引入router級中間件的好處之一是解耦,通過router去分層,然后app加載router。
3. HTTP的req對象
3.1 req.params取路徑參數
express中,路徑參數使用命名參數的方式,比如路徑是 /user/:id ,則使用 req.params.id 取參數 :id 的值,如:
/user/:id
GET /user/15
req.params.id => 15
3.2 req.query取查詢參數
取查詢參數,只需要通過 req.query 根據key取值即可,如:
GET /search?name=Ketty&gender=male
req.query.name => Ketty
req.query.gender => male
GET /search?user[name]=Ketty&user[age]=30
req.query.user.name => Ketty
req.query.user.age => 30
3.3 req.body
要取HTTP請求中的body內容,使用 req.body ,但是需要借助第三方module,如 body-parser 和 multer ,以下示例來自 express文檔 :
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
3.4 req.get()
提取HTTP header中的信息,其中,key是不區分大小寫的,如:
req.get('Content-Type'); // text/html
req.get('content-type'); // text/html
4. HTTP的res對象
4.1 res.status()
該方法僅僅是設置狀態碼,返回response還需調用 send()/end() 等方法,如:
res.status(200).end();
res.status(401).send("error: unauthorized!");
4.2 res.json()
返回json格式的信息,res會自動設置response的 Content-Type 為 application/json ,如:
res.status(401).json({"error": "unauthorized"});
4.3 res.send()
發送HTTP響應信息,參數可以是字符串、數組、Buffer對象等,會根據參數的類型自動設置header的 Content-Type ,如:
res.send(new Buffer("buffer info")); // Content-Type: application/octet-stream
res.send("<small>small text</small>"); // Content-Type: text/html
res.send({message: "Welcome"}); // Content-Type: application/json
4.4. res.set()
設置HTTP的header信息,如:
res.set('Content-Type','application/pdf');
res.setHeader('Content-Disposition','attachment; filename=cnb.pdf');
4.5 res.render()
使用模板引擎渲染頁面,然后作為response返回。如果參數表示的文件名不帶后綴,則會根據模板引擎的設置,自動推斷后綴;如果文件名帶后綴,則會加載該后綴對應的模板引擎模塊。如
res.render('index');
如果默認的模板引擎是jade,則express會從對應的路徑下查找index.jade文件并渲染。
來自:http://nkcoder.github.io/2016/08/20/express-tutorial-basic/