一 基本路由
路由用于确定程序如何响应对特定端点的客户机请求,包含一个URI(或路径)和一个特定的HTTP请求方法(GET、POST等)。
每个路由可以具有一个或者多个处理程序的函数,这些函数在路由匹配时执行。
路由定义采用以下结构:
app.METHOD(PATH,HANDLER);
其中:
- app是express的实例
- METHOD是HTTP请求方法
- PATH是服务器上的路径
- handler是路由匹配时执行的函数
有一种特殊路由的方法:app.all(),它并非派生自HTTP方法。该方法用于在所有请求方法的路径中装入中间件函数。
在以下示例中,无论您使用GET、POST、PUT、DELETE 还是在 http 模块中支持的其他任何 HTTP 请求方法,都将为针对“/secret”的请求执行处理程序。
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});
二 路由路径
路由路径与请求方法相结合,用于定义可以在其中提出请求的端点。路由路径可以是字符串、字符串模式或正则表达式。
以下是基于字符串的路由路径的一些示例。
(1)此路由路径将请求与根路由 /
匹配。
app.get('/', function (req, res) {
res.send('root');
});
(2) 此路由路径将请求与根路由
/remove/产品id/产品状态status
匹配。
router
.
post
(
'/remove/:id/:status'
,
function
(
req
,
res
,
next
) {
removeProduct
(
req
.
param
(
'id'
),
req
.
param
(
'status'
),
res
);
});
/random.text
匹配。
app.get('/random.text', function (req, res) {
res.send('random.text');
});
(4)
以下是基于字符串模式的路由路径的一些示例。
此路由路径将匹配 acd
和 abcd
。
app.get('/ab?cd', function(req, res) {
res.send('ab?cd');
});
(5)
此路由路径将匹配
abcd
、
abbcd
、
abbbcd
等。
app.get('/ab+cd', function(req, res) {
res.send('ab+cd');
});
三 路由处理程序
您可以提供多个回调函数,以类似于中间件的行为方式来处理请求。唯一例外是这些回调函数可能调用 next('route')
来绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,在没有理由继续执行当前路由的情况下,可将控制权传递给后续路由。
路由处理程序的形式可以是一个函数、一组函数或者两者的结合,
(1) 多个回调函数可以处理一个路由(确保您指定next
对象)。
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
(2) 一组回调函数可以由一个路由处理
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]);
(3)独立函数与一组函数可以由一个路由处理
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!');
});
四 响应方法