ExpressJS入門指南(二)

來源:互聯網
上載者:User
ExpressJS入門指南(二)

作者:chszs,轉載需註明。部落客頁:http://blog.csdn.net/chszs

緊接前一篇《ExpressJS入門指南》

六、使用express(1)產生應用

Express架構綁定了一個可執行指令碼,名為express(1)。如果使用npm對Express架構進行全域安裝,那麼express到處都能使用。

> npm install -g express

express(1)工具提供了簡單的產生應用程式骨架的方式,而且它有一定的使用範圍。比如它只支援有限的幾個模板引擎,而Express自身是支援任意Node構建的模板引擎。可以使用下面的命令進行查看:

> express --help

PS D:\tmp\node\hello-world> express --help

  Usage: express [options]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -s, --sessions      add session support
    -e, --ejs           add ejs engine support (defaults to jade)
    -J, --jshtml        add jshtml engine support (defaults to jade)
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet <engine> support (less|stylus) (defaults to plain css)
    -f, --force         force on non-empty directory

如果想產生支援EJS、Stylus、和會話Session的應用,那麼該這樣做:
> express --sessions --css stylus --ejs myapp
D:\tmp\node\hello-world>express --sessions --css stylus --ejs myapp

   create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.styl
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/user.js
   create : myapp/views
   create : myapp/views/index.ejs

   install dependencies:
     $ cd myapp && npm install

   run the app:
     $ node app

與其它Node應用一樣,必須安裝依賴包。
> cd myapp
> npm install

然後運行myapp,執行:
> node myapp.js

使用瀏覽器訪問地址:http://localhost:3000/
可以看到:
Express
Welcome to Express

這就是建立簡單應用的全過程。要記住,Express架構並沒有綁定任何指定的目錄結構,

七、Express架構說明

Express架構是Node.js第三方架構中比較好的Web開發架構。Express除了為HTTP模組提供了更高層的介面外,還實現了很多功能,其中包括:
1)路由控制;
2)模板解析支援;
3)動態視圖;
4)使用者會話;
5)CSRF保護;
6)靜態檔案服務;
7)錯誤控制器;
8)訪問日誌;
9)緩衝;
10)外掛程式支援。

要說明一點,Express並不是無所不包的全能架構(像Rails或Django那樣實現了模板引擎甚至是ORM),它只是一個輕量級的Web架構,其主要功能只是對HTTP協議中常用操作的封裝,更多的功能需要外掛程式或整合其它模組來完成。

比如:

var express = require('express');var app = express();app.use(express.bodyParser());app.all('/', function(req, res){res.send(req.body.title + req.body.text);});app.listen(3000);

聯繫我們

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