# 中间件

Express是一个路由和中间件Web框架,它具有自己的最小功能:Express应用程序本质上是一系列中间件函数调用。 中间件函数是可以访问请求对象 (req),响应对象(res)以及应用程序的请求 - 响应周期中的下一个中间件函数的函数。下一个中间件函数通常由名为的变量表示next。

中间件功能可以执行以下任务:

执行任何代码。 更改请求和响应对象。 结束请求 - 响应周期。 调用堆栈中的下一个中间件函数。 如果当前的中间件函数没有结束请求 - 响应周期,则必须调用next()以将控制传递给下一个中间件函数。否则,请求将被挂起。

An image

Express应用程序可以使用以下类型的中间件:

应用程序级中间件 路由器级中间件 错误处理中间件 内置中间件 第三方中间件

# supervisor 安装

npm install supervisor -g supervisor index.js 实现热启动

# public 输出目录静态资源

res.render()模版可以替换此方法

var express = require('express');
var app = express();
app.use(express.static('public'));

app.get('/index.html', function (req, res) {
    console.log(__dirname + "/views/" + "index.html");

    res.sendFile(__dirname + "/views/" + "index.html");

})

app.listen(8081, function () {
    console.log('Servver Start!');
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 标准的路由格式

controller/action 一个controller对应多个action

http://www.expressjs.com.cn/guide/routing.html

# 路由handle

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

app.get('/index/b', function (req, res, next) {
    console.log('response will be sent by the next function1 .....');
    next();
}, function (req, res, next) {
    console.log('response will be sent by the next function2 .....');
    next();
}, function (req, res, next) {
    console.log('结束');
    res.send('Hello world!');
},function(req, res, next) {
    console.log('接下来操作与客户端无关!');
});

app.listen(8000,function() {
    console.log('localhost://8000');
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var cb0 = function (req, res, next) {
    console.log('CB0')
    next()
}

var cb1 = function (req, res, next) {
    console.log('CB1')
    next()
}

var cb2 = function (req, res) {
    res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])


var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from D!')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# 错误处理

http://www.expressjs.com.cn/guide/error-handling.html

# 模版引擎

npm install swig