Express-guide 中文版(屌絲翻譯)

 

Getting started

開始

 

With node installed (download), get your first application started by creating a directory somewhere on your machine:javascript

當你安裝了node.js以後,你就能夠開始你的Node之旅。在開始建立一個應用以前,你首先要作的就是在你電腦的任意一個地方建立一個項目目錄。css

mkdir hello-world

In this same directory you'll be defining the application "package", which are no different than any other node package. You'll need a package.json file in the directory, with express defined as a dependency. You may use npm info express version to fetch the latest version, it's preferred that you do this instead of "3.x" below to prevent any future surprises.html

在這個目錄中你將定義項目的「包」,這裏所說的「包」跟其它的node包沒有什麼差異。你也須要在上述目錄中新建一個名爲package.json的文件,並將express定義成爲一個依賴項。你能夠在命令行/終端中輸入npm info express version 命令去獲取到最新的版本,可是仍是推薦使用以下添加依賴的方式來添加express,能夠減小一些沒必要要的麻煩。前端

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

Now that you have a package.json file in this directory you can use npm(1) to install the dependencies, in this case just Express:java

如今在你的文件夾中應該有一個package.json文件,這樣你就能夠經過npm命令來安裝項目須要的依賴,在這個例子中,目前的依賴只有express:node

npm install

Once npm finishes you'll have a localized Express 3.x dependency in the ./node_modules directory. You may verify this with npm ls as shown in the following snippet displaying a tree of Express and its own dependencies.git

當npm的操做完成以後,你的文件夾中將會有一個express 3.x 的依賴項在./node_modules目錄中。在項目的目錄中,你能夠經過npm ls 命令來查看項目中全部的依賴項,全部的依賴項將以樹狀結構進行顯示。github

$ npm ls
hello-world@0.0.1 /private/tmp
└─┬ express@3.0.0beta7
  ├── commander@0.6.1
  ├─┬ connect@2.3.9
  │ ├── bytes@0.1.0
  │ ├── cookie@0.0.4
  │ ├── crc@0.2.0
  │ ├── formidable@1.0.11
  │ └── qs@0.4.2
  ├── cookie@0.0.3
  ├── debug@0.7.0
  ├── fresh@0.1.0
  ├── methods@0.0.1
  ├── mkdirp@0.3.3
  ├── range-parser@0.0.4
  ├─┬ response-send@0.0.1
  │ └── crc@0.2.0
  └─┬ send@0.0.3
    └── mime@1.2.6

Now to create the application itself! Create a file named app.js or server.js, whichever you prefer, require express and then create a new application with express():redis

如今咱們就能夠開始真正的開發咱們的應用了,新建一個文件,命名爲app.js或者是server.js,在其中將express引入進來,而後在經過express()建立一個application對象。express

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

With the new application instance you can start defining routes via app.VERB(), in this case "GET /" responding with the "Hello World" string. The req and res are the exact same objects that node provides to you, thus you may invoke res.pipe(), req.on('data', callback) and anything else you would do without Express involved.

當具備一個application的實例的時候,你就能夠開始經過app.VERB()來創建路由了,在這裏經過get方式請求‘/’將返回「Hello World」字符串到頁面上,req,res是NODE爲你提供的對象,所以你能夠調用res.pipe(),req.on('data',callback)等方法。

app.get('/hello.txt', function(req, res){
  var body = 'Hello World';
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Content-Length', body.length);
  res.end(body);
});

Express augments these objects providing you with higher level methods such as res.send(), which among other things adds the Content-Length for you:

Express 提供的這些對象,擁有不少功能強大的方法,好比:res.send(),它會幫你設置Content-Length。

app.get('/hello.txt', function(req, res){
  res.send('Hello World');
});

Now to bind and listen for connections invoke the app.listen() method, accepting the same arguments as node's net.Server#listen():

接下來就是經過調用app.listen()方法來綁定並監聽端口,一樣你可使用NODE提供的net.Server#listen()

app.listen(3000);
console.log('Listening on port 3000');

 

Using express(1) to generate an app

使用express來生成一個工程

 

Express is bundled with an executable, aptly named express(1). If you install express globally with npm you'll have it available from anywhere on your machine:

Express綁定了一個名爲express的可執行程序。當你將express安裝成全局性的話,你能夠在你的電腦的任意目錄中使用它。

$ npm install -g express

This tool provides a simple way to get an application skeleton going, but has limited scope, for example it supports only a few template engines, whereas Express itself supports virtually any template engine built for node. Be sure to check out the --help:

使用這個工具咱們能夠簡單地建立應用程序的骨架。可是也存在一些限制,例如:express僅僅支持少許的模板引擎,然而express自己支持幾乎全部的用node編寫的模板引擎。在須要使用其它模板引擎的時候請先確認express是否支持該引擎。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   add stylesheet  support (less|stylus) (defaults to plain css)
  -f, --force         force on non-empty directory

If you want to generate an application with EJS, Stylus, and session support you would simply execute:

若是你想生成一個支持EJS,css,session的應用的話只須要簡單地執行一下命令:

$ 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/views
create : myapp/views/index.ejs

install dependencies:
  $ cd myapp && npm install
  
run the app:
  $ node app

Like any other node application, you must then install the dependencies:

就像創建其它的項目同樣你一樣須要安裝項目的依賴。

$ cd myapp
$ npm install

Then fire it up!

如今就能夠運行整個項目了。

$ node app.js

That's all you need to get a simple application up and running. Keep in mind that Express is not bound to any specific directory structure, these are simply a baseline for you to work from. For application structure alternatives be sure to view the examples found in the github repo.

想要一個簡單的應用程序可以運行起來,上述的步驟都是必須的。記住,Express沒有強制地規定目錄結構方面的細節,生成的目錄僅僅是給你提供一個簡單的工做目錄。做爲一個應用程序的目錄結構你能夠參照github上面的例子。

 

Error handling

錯誤處理

 

Error-handling middleware are defined just like regular middleware, however must be defined with an arity of 4, that is the signature (err, req, res, next):

Error-handling中間件就和其它的中間件同樣,只是它必須有4個參數,形如:(err, req, res, next)

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

Though not mandatory error-handling middleware are typically defined very last, below any other app.use() calls as shown here:

雖然沒有強制性的規定錯誤中間件放置的位置,可是一般狀況下咱們仍是應該把它放在最後,正以下面將中間件放在了全部的app.use()以後。

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

Responses from within these middleware are completely arbitrary. You may wish to respond with an HTML error page, a simple message, a JSON string, or anything else you prefer.

在中間件之間的響應信息都是任意的,你徹底能夠返回一個HTML的錯誤頁面,一條簡短的消息,一段json字符串等等。

For organizational, and higher-level framework purposes you may define several of these error-handling middleware, much like you would with regular middleware. For example suppose you wanted to define an error-handler for requests made via XHR, and those without, you might do:

對於一些具備高水平的框架,你可能會本身定義一些像你平時使用的中間件相似的錯誤處理的中間件。假設你想要去定義一個錯誤處理中間件去區別來自XHR(xml http request)的請求和其它的,你能夠這樣作:

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

Where the more generic logErrors may write request and error information to stderr, loggly, or similar services:

logErrors這個方法會將請求和錯誤信息一塊兒輸出到標準錯誤流,日誌或者是其它的服務程序中。

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

Where clientErrorHandler is defined as the following, note that the error is explicitly passed along to the next.

當clientErrorHandler被定義成下面這個樣子,須要注意的是,錯誤信息將被傳遞下去。

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

The following errorHandler "catch-all" implementation may be defined as:

下面這個實現方法幾乎能夠處理全部的錯誤信息。

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

 

Users online count

在線用戶計數

 

This section details a full (small) application that tracks a users online count using Redis. First up you'll need to create a package.json file containing two dependencies, one for the redis client, another for Express itself. Also make sure you have redis installed and running via $ redis-server.

本節咱們將使用redis來作一個跟蹤用戶在線數量的小程序。首先你得建立一個package.json文件並在其中添加兩個依賴項。一個是redis客戶端,一個就是express。同時應該確保你安裝的redis可以正常的使用。

{
  "name": "app",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.x",
    "redis": "*"
  }
}

Next you'll need to create an app, and a connection to redis:

接下來須要建立一個app實例,和一個連接redis的實例。

var express = require('express');
var redis = require('redis');
var db = redis.createClient();
var app = express();

Next up is the middleware for tracking online users. Here we'll use sorted sets so that we can query redis for the users online within the last N milliseconds. We do this by passing a timestamp as the member's "score". Note that here we're using the User-Agent string in place of what would normally be a user id.

接下來須要給跟蹤在線用戶數編寫一箇中間件。在這裏咱們將使用一個有序的集合,這樣咱們就能夠輕鬆地查詢到最近幾毫秒內的在線用戶數。咱們將傳入一個時間戳做爲一個用戶的「score」值,值得注意的是在這裏咱們將使用User-Agent來做爲一個用戶的ID.

app.use(function(req, res, next){
  var ua = req.headers['user-agent'];
  db.zadd('online', Date.now(), ua, next);
});

This next middleware is for fetching the users online in the last minute using zrevrangebyscore to fetch with a positive infinite max value so that we're always getting the most recent users, capped with a minimum score of the current timestamp minus 60,000 milliseconds.

接下來咱們要編寫一箇中間件去遍歷最近一分鐘的在線用戶,經過zrevrangebyscore函數去查詢上一分鐘的在線用戶,這樣咱們就能夠獲得從當前時間起在60000毫秒內的活躍用戶。

app.use(function(req, res, next){
  var min = 60 * 1000;
  var ago = Date.now() - min;
  db.zrevrangebyscore('online', '+inf', ago, function(err, users){
    if (err) return next(err);
    req.online = users;
    next();
  });
});

Then finally we use it, and bind to a port! That's all there is to it, visit the app in a few browsers and you'll see the count increase.

最後咱們使用如下代碼,並將其跟一個端口綁定起來,經過幾個瀏覽器來訪問這個程序了,你還能看到用戶數量的增加。

app.get('/', function(req, res){
  res.send(req.online.length + ' users online');
});

app.listen(3000);

 

Express behind proxies

給Express加一層代理

 

Using Express behind a reverse proxy such as Varnish or Nginx is trivial, however it does require configuration. By enabling the "trust proxy" setting via app.enable('trust proxy'), Express will have knowledge that it's sitting behind a proxy and that the X-Forwarded-* header fields may be trusted, which otherwise may be easily spoofed.

在express的前端使用反向代理好比Varnish,Nginx等都是沒必要要的,而且還須要配置。將「trust proxy」設置成enable(app.enable('true proxy')),Express就會知道在它以前還有一層代理,X-Forwarded-*頭信息應該被信任,可是這些頭信息也很容易被假裝。

Enabling this setting has several subtle effects. The first of which is that X-Forwarded-Proto may be set by the reverse proxy to tell the app that it is https or simply http. This value is reflected by req.protocol.

啓用這個設置將會出現一些微妙的效果,其中之一就是頭信息中X-Forwarded-Proto字段將被反向代理服務器設置,並告訴應用程序使用的是HTTPS仍是HTTP,這個值能夠經過req.protocol獲得。

The second change this makes is the req.ip and req.ips values will be populated with X-Forwarded-For's list of addresses.

第二個變化就是req.ip和req.ips將會被X-Forwarded-For中設置的值填充。

 

Debugging Express

調試

 

Express uses the debug module internally to log information about route matches and application mode. To see this information, simply set the DEBUG environment variable to express:* when launching your app and the debug information will appear on the console.

Express經過使用內部的debug模塊來將路由,模型等信息以日誌的方式記錄下來。能夠經過簡單的設置Express中的DEBUG,當程序運行起來後你就能夠在控制檯中看見調試信息了。

$ DEBUG=express:* node app.js

Running this on the hello world example would print the following.

將這一條命令運行在hello-world項目中,就會顯示出以下信息。  

express:application booting in development mode +0ms
express:router defined get /hello.txt +0ms
express:router defined get /hello.txt +1ms

For more documentation on debug, see the debug guide.

想要查看debug的更多文檔信息,能夠訪問debug guide。

相關文章
相關標籤/搜索