透析Express.js

來源:互聯網
上載者:User

標籤:

前言

    最近,本屌在試用Node.js,在尋找靠譜web架構時發現了Express.js。Express.js在Node.js社區中是比較出名web架構,而它的定位是“minimal and flexible(簡潔、靈活)”。

 

進擊的Express.js1. 底層的Http module

    Node有Http module,本質上,我們可以直接通過他寫Web應用。Http module使用很簡單:

////////////////// app.js////////////////// 載入所需模組var http = require("http");// 建立Servervar app = http.createServer(function(request, response) {  response.writeHead(200, {    "Content-Type": "text/plain"  });  response.end("Hello hyddd!\n");});// 啟動Serverapp.listen(1984, "localhost");

    運行node app.js。訪問http://localhost:1984,即可看到“Hello hyddd!”。

    現在問題來了,Web需要通過不同uri區分功能,如:/user/profile 表示使用者資訊,/about 表示網站簡介……,而Http module並沒有直接提供dispatch功能,當然,自己實現也不難:

////////////////// app1.js////////////////// 載入所需模組var http = require("http");// 建立Servervar app = http.createServer(function(request, response) {  if(request.url == ‘/‘){    response.writeHead(200, { "Content-Type": "text/plain" });    response.end("Home Page!\n");  } else if(request.url == ‘/about‘){    response.writeHead(200, { "Content-Type": "text/plain" });    response.end("About Page!\n");  } else{    response.writeHead(404, { "Content-Type": "text/plain" });    response.end("404 Not Found!\n");  }});// 啟動Serverapp.listen(1984, "localhost");

    如果要區別對待Http method,可以根據 request.method 判斷。至此,Http module在此情境下的短板顯露無疑。

 
2. 中介層:Middleware

    什麼是middleware?根據牛文《A short guide to Connect Middleware》裡定義,middleware就是一大坨handle requests的funcions。

    這裡說明下,middleware是一個概念;而上面的Connect,是一個Http Server Framework,基於Http module擴充,可以說它是Express.js的前身。所以可以把Connect等價看作Express.js。先看個Demo:

////////////////// app2.js////////////////// 載入所需模組var express = require("express");var http = require("http");// 建立servervar app = express();// 增加一些middlewareapp.use(function(request, response, next) {  console.log("step1, url:" + request.url);  next();});app.use(function(request, response, next) {  console.log("step2");  if(request.url == ‘/‘){    response.writeHead(200, { "Content-Type": "text/plain" });    response.end("Main Page!\n");  }  next();});app.use(function(request, response, next) {  console.log("step2:");  console.log("step3");  if(request.url == ‘/about‘){      response.writeHead(200, { "Content-Type": "text/plain" });      response.end("About Page!\n");  }});// 啟動serverhttp.createServer(app).listen(1984);

     運行node app.js,訪問:http://localhost:1984/,console結果是:

    step1,url:/

    step2

    Express通過 app.use 註冊middleware,middlewares相當於request的handlers,在處理request時,順序執行每一個handler(function),handler業務完成後,通過調用next();,決定是否調用下一個handler,說白了就是 鏈 處理。

    Middleware是Express.js非常重要的特性,沒有之一。基於這個特性,Express.js繼續實現了routing-dispatch(讓你可以優雅地寫request處理函數), 公用的error處理(404,500處理),提供機制給開發人員實施許可權校正機制等等。而在各種Express.js文檔中,這塊的篇幅是最長的,Express.js很多的變化和淫蕩技巧會在middleware得到體現。

 

3.1 頂層:Routing

    app2.js的裡,雖然通過middleware方式,把“/”和“/about”獨立出來,但和優雅的高可讀代碼還沒半毛錢關係。Routing是基於Middleware特性,它其實就是匹配不同的request到不同的handler上:

////////////////// app3.js////////////////var express = require("express");var http = require("http");var app = express();app.all("*", function(request, response, next) {  console.log("step1");  next();});app.get("/", function(request, response) {  response.end("Home Page!");});app.get("/about", function(request, response) {  response.end("About Page!");});app.get("*", function(request, response) {  response.end("404!");});http.createServer(app).listen(1984);

    這樣確實優雅了許多,至於更多的奇淫技巧可以參看各種文檔。

 

3.2 頂層:Views

    額,Express加入了View處理機制,一起看看:

var express = require("express");var app = express();// 模板目錄:./viewsapp.set("views", __dirname + "/views");// 使用jade引擎app.set("view engine", "jade"); // 定址views/index,提交jade渲染,並返回結果app.get("/", function(request, response) { response.render("index", { message: "I‘m hyddd" }); });

    Express的View機制還是簡單的。

 

3.3 頂層:其他“小”特性

    我之所以稱其他特性為“小”特性,是因為他們相對前兩者(特別是Routing),在架構中的地位都是次要的。

    舉個栗子:response,Express的response基於Http.Server的response擴充,提供了一些新功能,如:response.redirect("/user/login"); 和 response.sendFile("/path/to/file");。

    其他的,大家可以參考官方文檔。

 

總結

    Express正如官網中的描述一樣“minimal and flexible”。Express主要解決了 請求路由 和 視圖模板 的問題,其中Middleware是它最重要的概念。它是不錯的Web架構,但本屌還是有些想法的:

    1. Express不是MVC的架構,因為它沒有對Model解決方案。嗯,有點廢話,因為Express本身定位就不是MVC,只是minimal and flexible的Web架構。

    2. 由於Express實在是flexible,沒有強制的規範約束,加上js是可以把代碼寫得很隨意的程式設計語言,所以本屌找到的Demo中,Config,Controller,View的維護、管理、技巧都可能各式各樣。

    所以,沒有明確Model解決方案(當然你可以找第三方的)和弱規範約束,使整天踩在別人(巨人)肩膀上的本屌開始時不太適應。

 

參考資料

1. 《understanding-express》

2. 《A short guide to Connect Middleware》

3. 《expressjs官方文檔》

透析Express.js

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.