Express介紹

npm提供了大量的第三方模塊,其中不乏許多Web框架,比如我們本章節要講述的一個輕量級的Web框架 ——— Express。

  Express是一個簡潔、靈活的node.js Web應用開發框架, 它提供一系列強大的功能,比如:模板解析、靜態文件服務、中間件、路由控制等等,並且還可以使用插件或整合其他模塊來幫助你創建各種 Web和移動設備應用,是目前最流行的基於Node.js的Web開發框架,並且支持Ejs、jade等多種模板,可以快速地搭建一個具有完整功能的網站。
NPM安裝

 npm install express

獲取、引用

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

通過變量“app”我們就可以調用express的各種方法了

**路由**
// 對網站首頁的訪問返回 "Hello World!" 字樣
app.get('/', function (req, res) {
  res.send('Hello World!');
});

// 網站首頁接受 POST 請求
app.post('/', function (req, res) {
  res.send('Got a POST request');
});

// /user 節點接受 PUT 請求
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user');
});

// /user 節點接受 DELETE 請求
app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user');
});

Express 定義瞭如下和 HTTP 請求對應的路由方法: get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search, 和 connect。
app.all是對於一個路徑上的所有請求加載中間件:

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

使用字符串模式的路由路徑示例:

// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});

// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});

// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});

使用正則表達式的路由路徑示例:

// 匹配任何路徑中含有 a 的路徑:
app.get(/a/, function(req, res) {
  res.send('/a/');
});

// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等
app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

使用多個回調函數處理路由(記得指定 next 對象):

app.get('/example/b', function (req, res, next) {
  console.log('response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});

使用回調函數數組處理路由:

var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

var cb2 = function (req, res) {
  res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);

混合使用函數和函數數組處理路由:

var cb0 = function (req, res, next) {
  console.log('CB0');
  next();
}

var cb1 = function (req, res, next) {
  console.log('CB1');
  next();
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from D!');
});

響應方法
res.download() 提示下載文件。
res.end() 終結響應處理流程。
res.json() 發送一個 JSON 格式的響應。
res.jsonp() 發送一個支持 JSONP 的 JSON 格式的響應。
res.redirect() 重定向請求。
res.render() 渲染視圖模板。
res.send() 發送各種類型的響應。
res.sendFile 以八位字節流的形式發送文件。
res.sendStatus() 設置響應狀態代碼,並將其以字符串形式作爲響應體的一部分發送。
使用 app.route() 定義了鏈式路由句柄:

app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });

可使用 express.Router 類創建模塊化、可掛載的路由句柄:

var express = require('express');
var router = express.Router();

// 該路由使用的中間件
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// 定義網站主頁的路由
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// 定義 about 頁面的路由
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

然後在應用中加載路由模塊:

var birds = require('./birds');
...
app.use('/birds', birds);

應用即可處理髮自 /birds 和 /birds/about 的請求,並且調用爲該路由指定的 timeLog 中間件。
應用級中間件綁定到 app 對象 使用 app.use() 和 app.METHOD():

var app = express();

// 沒有掛載路徑的中間件,應用的每個請求都會執行該中間件
app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

// 掛載至 /user/:id 的中間件,任何指向 /user/:id 的請求都會執行它
app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

// 路由和句柄函數(中間件系統),處理指向 /user/:id 的 GET 請求
app.get('/user/:id', function (req, res, next) {
  res.send('USER');
});

在一個掛載點裝載一組中間件:

// 一箇中間件棧,對任何指向 /user/:id 的 HTTP 請求打印出相關信息
app.use('/user/:id', function(req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

通過 Express 內置的 express.static 可以方便地託管靜態文件,例如圖片、CSS、JavaScript 文件等。
將靜態資源文件所在的目錄作爲參數傳遞給 express.static 中間件就可以提供靜態資源文件的訪問了。例如,假設在 public 目錄放置了圖片、CSS 和 JavaScript 文件,你就可以:

app.use(express.static('public'));

現在,public 目錄下面的文件就可以訪問了。

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

所有文件的路徑都是相對於存放目錄的,因此,存放靜態文件的目錄名不會出現在 URL 中。
如果你希望所有通過 express.static 訪問的文件都存放在一個“虛擬(virtual)”目錄(即目錄根本不存在)下面,可以通過爲靜態資源目錄指定一個掛載路徑的方式來實現,如下所示:

app.use('/static', express.static('public'));

現在,你就愛可以通過帶有 “/static” 前綴的地址來訪問 public 目錄下面的文件了。

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

渲染模板文件:
views, 放模板文件的目錄,比如: app.set(‘views’, ‘./views’)
view engine, 模板引擎,比如: app.set(‘view engine’, ‘jade’)
錯誤處理
錯誤處理中間件和其他中間件定義類似,只是要使用 4 個參數,而不是 3 個,其簽名如下: (err, req, res, next)。

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

在其他 app.use() 和路由調用後,最後定義錯誤處理中間件,比如:

var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.use(bodyParser());
app.use(methodOverride());
app.use(function(err, req, res, next) {
  // 業務邏輯
});
發佈了9 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章