Express框架入門

express 是nodejs的一個流行的web框架。本文主要介紹將express做爲服務端對外提供API接口時,須要瞭解的入門知識。html

1. Hello World

首先安裝node(若是已安裝,則略過):node

$ brew install node

建立一個項目,而後安裝express:web

$ mkdir express-hello-world && cd express-hello-world
$ npm init
$ npm install express --save

npm init 會提示輸入一些配置信息,回車使用默認值便可,執行完後,當前目錄下會自動建立 package.json 文件。express

npm install express --save 表示爲當前項目安裝express依賴,該依賴信息會保存在 package.json 文件中。npm

新建文件 index.js 文件, 輸入如下內容:json

var express =  require('express');
var app = express();

app.get('/', function(req, res) {
  res.send('hello, world!');
});

app.listen(3000);

運行:api

$ 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()表示將執行傳遞給調用棧中的下一個中間件函數。app

若是當前中間件函數沒有結束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文件並渲染。

相關文章
相關標籤/搜索