Node.js:Express 入門和基礎知識
Express 是一個自身功能極簡,完全是由路由和中介軟體構成一個的web 開發框架:從本質上來說,一個 Express 應用就是在呼叫各種中介軟體。
初始化
新建一個目錄myapp,專案初始化
$ npm init
安裝express
$ npm install express --save
建立一個hello world例項
進入myapp目錄,建立一個名為app.js,複製以下程式碼
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
上面的程式碼啟動一個服務並監聽從 3000 埠進入的所有連線請求。他將對所有 (/) URL 或 路由 返回 “Hello World!” 字串。對於其他所有路徑全部返回 404 Not Found。
通過以下命令列啟動
$ node app.js
然後在瀏覽器中開啟http://localhost:3000/ 並檢視輸出結果。
express生成器
通過應用生成器工具 express 可以快速建立一個應用的骨架。
1.安裝以下命令
//code from http://caibaojian.com/express-basic.html $ npm install express-generator -g
2.在當前目錄建立myapp的應用,執行以下命令·
$ express myapp $ cd myapp $ npm install > set DEBUG=myapp & npm start
然後在瀏覽器中開啟http://localhost:3000/ 網址就可以看到這個應用了。
通過 Express 應用生成器建立的應用一般都有如下目錄結構:
. ├── app.js ├── bin │└── www ├── package.json ├── public │├── images │├── javascripts │└── stylesheets │└── style.css ├── routes │├── index.js │└── users.js └── views ├── error.jade ├── index.jade └── layout.jade 7 directories, 9 files
express路由
路由(Routing)是由一個 URI(或者叫路徑)和一個特定的HTTP 方法(GET、POST 等)組成的,涉及到應用如何響應客戶端對某個網站節點的訪問。每一個路由都可以有一個或者多個處理器函式,當匹配到路由時,這個/些函式將被執行。
路由的定義由如下結構組成:app.METHOD(PATH, HANDLER)。其中,app 是一個 express 例項;METHOD 是某個 HTTP 請求方式中的一個;PATH 是伺服器端的路徑;HANDLER 是當路由匹配到時需要執行的函式。
以下是一些常見的路由程式碼
var express = require('express'); var app = express(); // respond with "hello world" when a GET request is made to the homepage app.get('/', function(req, res) { res.send('hello world'); }); // POST method route app.post('/', function (req, res) { res.send('POST request to the homepage'); }); //app.all() 是一個特殊的路由方法,沒有任何 HTTP 方法與其對應,它的作用是對於一個路徑上的所有請求載入中介軟體。 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('route') 方法而略過其他路由回撥函式。
路由控制代碼有多種形式,可以是一個函式、一個函式陣列,或者是兩者混合,如下所示
//使用多個回撥函式處理路由(記得指定 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]);
響應方法
下表中響應物件(res)的方法向客戶端返回響應,終結請求響應的迴圈。如果在路由控制代碼中一個方法也不呼叫,來自客戶端的請求會一直掛起。
方法 描述
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() 建立路由路徑的鏈式路由控制代碼。由於路徑在一個地方指定,這樣做有助於建立模組化的路由,而且減少了程式碼冗餘和拼寫錯誤。
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
可使用 express.Router 類建立模組化、可掛載的路由控制代碼。Router 例項是一個完整的中介軟體和路由系統,因此常稱其為一個 “mini-app”。
在 app 目錄下建立名為 birds.js 的檔案,內容如下:
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 中介軟體。
利用 Express 託管靜態檔案
通過 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
如果你的靜態資源存放在多個目錄下面,你可以多次呼叫 express.static 中介軟體:
app.use(express.static('public')); app.use(express.static('files'));
如果你希望所有通過 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
常見問題
如何處理 404 ?
在 Express 中,404 並不是一個錯誤(error)。因此,錯誤處理器中介軟體並不捕獲 404。這是因為 404 只是意味著某些功能沒有實現。也就是說,Express 執行了所有中介軟體、路由之後還是沒有獲取到任何輸出。你所需要做的就是在其所有他中介軟體的後面新增一個處理 404 的中介軟體。如下:
app.use(function(req, res, next) { res.status(404).send('Sorry cant find that!'); });
Express 支援哪些模板引擎?
Express 支援任何符合 (path, locals, callback) 介面規範的模板引擎。具體可看這個專案:https://github.com/tj/consolidate.js
如何渲染純HTML 檔案?
不需要!無需通過 res.render() 渲染 HTML。你可以通過 res.sendFile() 直接對外輸出 HTML 檔案。如果你需要對外提供的資原始檔很多,可以使用 express.static() 中介軟體。