Express ( MiddleWare/中间件 路由 在 Express 中使用模板引擎 常用API

 A fast, un-opinionated, minimalist web framework for Node.js applications. In general, prefer simply “Express” to “Express.js,” though the latter is acceptable.

Express 是一个自身功能极简,完全是由路由和中间件构成一个的 web 开发框架:从本质上来说,一个 Express 应用就是在调用各种中间件。

阮一峰express教程  官方网站   中文官方文档    Express 3.x API 中文手册

middleware 

 官方文档 使用中间件

通俗地讲,中间件(middleware)就是处理HTTP请求的函数

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

中间件函数可以access请求对象、返回对象和下一个中间件函数。

A function invoked by the Express routing layer before the final request handler, and thus sits in the middle between a raw request and the final intended route. A few fine points of terminology around middleware:

  • var foo = require('middleware') is called requiring or using a Node.js module. Then the statement var mw = foo() typically returns the middleware.
  • app.use(mw) is called adding the middleware to the global processing stack.
  • app.get('/foo', mw, function (req, res) { ... }) is called adding the middleware to the “GET /foo” processing stack.

Middleware functions can perform the following tasks:

  • Execute any code.  执行任何代码
  • Make changes to the request and the response objects. 对请求对象,返回对象做出任何改动
  • End the request-response cycle.           结束“请求-返回”循环
  • Call the next middleware in the stack.   调用下一个中间件函数。调用堆栈中的下一个中间件。

Notice the call above to next(). Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next() function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.

call to next()来触发下一个中间件函数。next()不是node.js或express的一部分,但是是第三个参数。可以起任何的名字,但约定俗成为next().

Express的MiddlewareMiddleware这个函数接受express传入3个参数:req,res和next。调用的方法就是app.use(function(req,res,next){....}); 从处理过程上来看,middleware是处在请求Request和最终处理请求的Route Handler之间的一系列函数,它对于请求的内容在交由Route Handler之前做预先的处理。例如下面在请求到达route handler处理之前,经由Middleware的处理将请求的方法和地址打印在console中。

Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.

因为你可以获取请求对象,返回对象,中间件函数和node.js的全部api,所以中间件函数有无穷的可能。

路由

路由是指如何定义应用的端点(URIs)以及如何响应客户端的请求。

路由是由一个 URI、HTTP 请求(GET、POST等)和若干个句柄组成,它的结构如下: app.METHOD(path, [callback...], callback), app 是 express对象的一个实例, METHOD 是一个 HTTP 请求方法, path 是服务器上的路径, callback 是当路由匹配时要执行的函数。

下面是一个基本的路由示例:

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

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
  res.send('hello world');
});

Express 定义了如下和 HTTP 请求对应的路由方法: get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search, 和 connect。

app.all()

app.all()是一个特殊的路由方法,没有任何 HTTP 方法与其对应,它的作用是对于一个路径上的所有请求加载中间件。

路由句柄

可以为请求处理提供多个回调函数,其行为类似 中间件。唯一的区别是这些回调函数有可能调用 next('route') 方法而略过其他路由回调函数。可以利用该机制为路由定义前提条件,如果在现有路径上继续执行没有意义,则可将控制权交给剩下的路径。

路由句柄有多种形式,可以是一个函数、一个函数数组,或者是两者混合,如下所示.

响应方法

下表中响应对象(res)的方法向客户端返回响应,终结请求响应的循环如果在路由句柄中一个方法也不调用,来自客户端的请求会一直挂起。

res.download 提示下载文件。
res.end() 终结响应处理流程。
res.json() 发送一个 JSON 格式的响应。
res.jsonp() 发送一个支持 JSONP 的 JSON 格式的响应。
res.redirect() 重定向请求。
res.render() 渲染视图模板。
res.send() 发送各种类型的响应。
res.sendFile 以八位字节流的形式发送文件。
res.sendStatus() 设置响应状态代码,并将其以字符串形式作为响应体的一部分发送。

在 Express 中使用模板引擎

需要在应用中进行如下设置才能让 Express 渲染模板文件:

  • views, 放模板文件的目录,比如: app.set('views', './views')
  • view engine, 模板引擎,比如: app.set('view engine', 'jade')

 

常用API

express()

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

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

app.listen(3000);

Creates an Express application. The express() function is a top-level function exported by the express module(是express模块“暴露出来的”).

express.static()

是 Express 唯一内置的中间件。它基于 serve-static,负责在 Express 应用中提托管静态资源。参数 root 指提供静态资源的根目录。

.set()

set方法用于指定变量的值。

app.set("views", __dirname + "/views");

app.set("view engine", "jade");

上面代码使用set方法,为系统变量“views”和“view engine”指定值。

.use()

 To load the middleware function, call app.use(), specifying the middleware function. 

use是express注册中间件的方法,它返回一个函数。

The order of middleware loading is important: middleware functions that are loaded first are also executed first.

中间件函数加载的顺序很重要,按顺序执行。

app.all()

app.all()是一个特殊的路由方法,没有任何 HTTP 方法与其对应,它的作用是对于一个路径上的所有请求加载中间件。

 response.redirect()

 response.redirect方法允许网址的重定向。

response.sendFile()

res.sendfile(path, [options], [fn]])

response.sendFile方法用于发送文件

response.render()

response.render方法用于渲染网页模板。

Render a view with a callback responding with the rendered string. When an error occurs next(err) is invoked internally. When a callback is provided both the possible error and rendered string are passed, and no automated response is performed.

request.ip

request.ip属性用于获得HTTP请求的IP地址。

request.files

request.files用于获取上传的文件。

Node.js

 

__dirname:开发期间,该行代码所在的目录。

module.filename:开发期间,该行代码所在的文件。

exports对象:你可以用它创建你的模块。

module.exports: 才是真正的接口,exports只不过是它的一个辅助工具。

 

posted on 2016-11-07 21:21  oneplace  阅读(592)  评论(0编辑  收藏  举报

导航