Express框架-路由
你将会学习Express路由,包括以下几点
- 路由的定义
- 路由中间件
- 模块化的路由
什么是路由?
路由指的是通过URI来定义一个应用程序如何响应客户端请求
Express基本路由
A route is a combination of a URI, a HTTP request method (GET, POST, and so on), and one or more handlers for the endpoint. It takes the following structure app.METHOD(path, [callback…], callback), where app is an instance of express, METHOD is an HTTP request method, path is a path on the server, and callback is the function executed when the route is matched
路由是URI和HTTP请求方法(GET, POST, 包括其它的)的组合,这里的app是express的一个实例,method是HTTP请求方法,path是一个服务器端的路径,当匹配该路由的时候的就会执行回调函数
基本路由的构造
app.get('/user/:id', function(req, res) {
res.send('user ' + req.params.id);
});
Route methods(路由方法)
A route method is derived from one of the HTTP methods, and is attached to an instance of express.
路由的方法派生自HTTP的方法,并且附加在express的实例上
// GET method route GET方法路由
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});
// POST method route POST路由方法
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
Express supports the following routing methods corresponding to HTTP methods: 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, and connect
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, and connect
To route methods which translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ...
路由的方法是无法通过变量转换的,比如
app['m-search']('/', function (){
//code ......
}
There is a special routing method, app.all(), which is not derived from any HTTP method. It is used for loading middleware at a path for all request methods.
app.all()是特殊的路由方法,它不是派生自http的方法,它常用于在所有请求中载入中间件
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler 转到下一个处理程序
});
Route paths 路由路径
Route paths, in combination with a request method, define the endpoints at which requests can be made to. They can be strings, string patterns, or regular expressions.
路由路径,当定义请求方法时和请求方法组合使用,它可以是字符串或者正则表达式,字符串匹配模式
Query strings are not a part of the route path.
查询字符串不是组成路由路径的一部分
字符串
// 将会匹配请求
app.get('/', function (req, res) { res.send('root');
});
// 将会匹配/about 请求
app.get('/about', function (req, res) { res.send('about');
});
// 将会匹配/ramdom.tex请求
app.get('/random.text', function(req, res) {
res.send('random.text');
});
正则表达式
// 将会匹配 acd and abcd
app.get('/ab?cd', function(req, res) { res.send('ab?cd'); });
// 将会匹配 abcd, abbcd, abbbcd, and so on
app.get('/ab+cd', function(req, res) {
res.send('ab+cd');
});
// 将会匹配 abcd, abxcd, abRABDOMcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
res.send('ab*cd');
});
// 将会匹配 /abe and /abcde
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e');
});
Route handlers
You can provide multiple callback functions that behave just like middleware to handle a request. The only exception is that these callbacks may invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
你可以提供多个回调函数,就像请求中间件的处理程序,通过next就可以交给下一个回调函数
A route can be handled using a more than one callback function (make sure to specify the next object):路由能够使用多个回调函数(确保你已经指定next对象)
路由的回调参数可以是回调函数的数组
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('response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from D!');
});
Response methods 响应方法
Chainable route handlers for a route path can be created using app.route(). Since the path is specified at a single location, it helps to create modular routes and reduce redundancy and typos. For more information on routes, see Router() documentation.
链式路由是使用app.route创建的,它可以帮助你创建模块化的路由,并且减少冗余代码
app.route('/book') .get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});
The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.
express.Router() 类可用来创建模块化的路由程序,一个路由实例是一个完整的中间件和路由系统
var express = require('express');
var router = express.Router();
// middleware specific to this router 为这个路由指定中间件
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now()); next();
});
// define the home page route 定义home路由
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route 定义about路由
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
载入路由模块
var birds = require('./birds');
使用
app.use('/birds', birds);