Express入門( node.js Web應用程式框架 )

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   使用   ar   

運用Express架構構建簡單的NodeJS應用

 

Start 

  確認安裝了NodeJS之後(最新的Node安裝好後NPM也會內建安裝了),npm可理解為nodejs的一個工具包。可通過查看版本來檢測是否安裝成功:

F:\>node -vv0.10.32F:\>npm -v1.4.28

建立一個目錄,在這個目錄中首先得定義一下應用程式“包”檔案,它和其它的node程式包是一樣的。 即在這個目錄中建立一個package.json檔案,在裡面express作為一個依賴。 你也可以使用 npm info express version 來擷取express最新的版本號碼, 最好使用最新的版本號碼而不是下面的3.x,這樣新出的功能就不會讓你感覺到奇怪了。

F:\>npm info express versi4.9.5F:\>mkdir HelloNode

手動建立一個應用程式依賴的包檔案package.json:

{  "name": "hello-world",  "description": "hello world test app",  "version": "0.0.1",  "private": true,  "dependencies": {    "express": "3.x"  }
"scripts": {
      "start": "forever app.js", 
"test": "supervisor app.js"
}
}

package.json檔案是非常重要的,至少我是這麼認為的,dependencies欄位指定的是程式依賴的程式包,只要在這裡指定,npm install時會自動安裝這裡面指定的所有包。scripts欄位也比較常用的,如上面,如果啟動程式,可以用"npm start"或者"npm test"命令,指定supervisor表示可以自動探測程式改變。

 

package.json檔案準備好後,運行npm install命令,則會安裝檔案中指定的依賴的包,

F:\>cd HelloNode && npm install[email protected]3.17.6 node_modules\express├── basic[email protected]├── merge[email protected]├── [email protected]0.2.4├── escape[email protected]├── [email protected]0.1.2├── range[email protected]├── cookie[email protected]├── [email protected]1.0.0├── media[email protected]├── [email protected]1.3.0├── [email protected]1.1.0├── [email protected]0.4.5├── [email protected]3.0.0├── [email protected]0.5.0 ([email protected])├── [email protected]2.0.0 ([email protected])├── [email protected]1.3.2 ([email protected])├── proxy[email protected] ([email protected], [email protected])├── [email protected]0.9.3 ([email protected], [email protected], [email protected], [email protected], on-finished@2.1.0)└── [email protected]2.26.4 ([email protected], [email protected], [email protected].0, [email protected], [email protected], [email protected], [email protected], on-heade[email protected]1.0.0, [email protected], [email protected], [email protected], [email protected].1.5, [email protected], [email protected], [email protected], [email protected], serve-[email protected]1.2.1, [email protected], [email protected], [email protected], [email protected]1.6.1, [email protected])

當npm完成後,Express 3.x 和它的依賴就安裝到當前的 node_modules 目錄裡了(這個目錄會自動建立,裡面是安裝的依賴包)。 可以通過 npm ls 來確認一下,它會把Express 和它的依賴展示成下面的樹狀結構。

[email protected] /private/tmp└─┬ [email protected]3.0.0beta7  ├── [email protected]0.6.1  ├─┬ [email protected]2.3.9  │ ├── [email protected]0.1.0  │ ├── [email protected]0.0.4  │ ├── [email protected]0.2.0  │ ├── [email protected]1.0.11  │ └── [email protected]0.4.2  ├── [email protected]0.0.3  ├── [email protected]0.7.0  ├── [email protected]0.1.0  ├── [email protected]0.0.1  ├── [email protected]0.3.3  ├── range[email protected]  ├─┬ response[email protected]  │ └── [email protected]0.2.0  └─┬ [email protected]0.0.3    └── [email protected]1.2.6

環境準備好了,我們可以建立一個應用程式了,在目錄下建立一個檔案app.js(anyway,名字隨便取的,習慣叫app.js),app.js的內容如下:(實際上是載入express架構,讓後建立一個應用程式)

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

然後就是定義路由,即響應使用者要訪問的路徑,Express 給這些對象加了一個封裝好的方法,比如 res.send(), 它會設定Content-Length,只要調用send方法就好:

app.get(‘/hello.txt‘, function(req, res){  res.send(‘Hello NodeJS!!‘);});

然後通過執行 app.listen() 來綁定並監聽串連:

var server = app.listen(3000, function() {    console.log(‘Listening on port %d‘, server.address().port);});

上面3段都是app.js的內容。

然後啟動程式,在目前的目錄下直接打"node app.js"即可:

F:\HelloNode>node app.jsListening on port 3000

然後訪問http://127.0.0.1:3000/ 即可,介面如下:

用Express啟動一個nodejs應用程式,so easy!

 

使用express來產生一個應用程式

其實還有更簡潔的方法,即用express產生node應用程式的模板,那些檔案都不用自己建立,直接一個命令就能把常用的檔案和包都裝好,這對我們懶人來說真是百年難遇的特大福利。

運行express myapp即可產生如下目錄的檔案:

如上提示,cd mypp && npm install 然後node app即可啟動程式。

如果你想產生一個支援Jade, Stylus的應用程式,只需要簡單的執行下面的命令:

 express --sessions --css stylus --ejs myapp

 

以上安裝的軟體均不是全域的,只是在目前的目錄程式下有用。

錯誤處理

錯誤處理的中介軟體和普通的中介軟體定義是一樣的, 只是它必須有4個形參,這是它的形式: (err, req, res, next):

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

一般來說非強制性的錯誤處理一般被定義在最後,下面的代碼展示的就是放在別的 app.use() 之後:

app.use(express.bodyParser());app.use(express.methodOverride());app.use(app.router);app.use(function(err, req, res, next){  // logic});

在這些中介軟體裡的響應是可以任意定義的,可以返回任意的內容,譬如HTML頁面, 一個簡單的訊息,或者一個JSON字串。

對於一些組織或者更高層次的架構,可能會像定義普通的中介軟體一樣定義一些錯誤處理的中介軟體。 假設想定義一個中介軟體區別對待通過XHR和其它請求的錯誤處理,你可以這麼做:

app.use(express.bodyParser());app.use(express.methodOverride());app.use(app.router);app.use(logErrors);app.use(clientErrorHandler);app.use(errorHandler);

通常logErrors用來紀錄諸如stderr, loggly, 或者類似服務的錯誤資訊:

function logErrors(err, req, res, next) {  console.error(err.stack);  next(err);}

clientErrorHandler 定義如下,注意錯誤非常明確的向後傳遞了。

function clientErrorHandler(err, req, res, next) {  if (req.xhr) {    res.send(500, { error: ‘Something blew up!‘ });  } else {    next(err);  }}

下面的errorHandler "捕獲所有" 的異常, 定義為:

function errorHandler(err, req, res, next) {  res.status(500);  res.render(‘error‘, { error: err });}

 

 

Express入門( node.js Web應用程式框架 )

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.