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。

相关文章
相关标签/搜索