NodeJS之express的路由浅析

路由路径和请求方法一块儿定义了请求的端点,它能够是字符串、字符串模式或者正则表达式。后端在获取路由后,可经过一系列相似中间件的函数去执行事务。html

可以使用字符串的路由路径:正则表达式

// 匹配根路径的请求
app.get('/', function (req, res) {
  res.send('root');
});

// 匹配 /about 路径的请求
app.get('/about', function (req, res) {
  res.send('about');
});

// 匹配 /random.text 路径的请求
app.get('/random.text', function (req, res) {
  res.send('random.text');
});

可以使用字符串模式的路由路径:express

// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});

可以使用正则表达式的路由路径:后端

// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等
app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

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

路由句柄有多种形式,能够是一个函数、一个函数数组,或者是二者混合,以下所示app

使用一个回调函数处理路由:dom

app.get('/example', function (req, res) {
  res.send('Hello from A!');
});

使用多个回调函数处理路由(记得指定 next 对象):ide

app.get('/example/b', function (req, res, next) {
  console.log('response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});

使用回调函数数组处理路由:模块化

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!');
});

 

可以使用 express.Router 类建立模块化、可挂载的路由句柄。Router 实例是一个完整的中间件和路由系统。

var log=require("./log/log");
var express=require("express");
var app=express();

//首先定义一个路由
var router=express.Router();

//使用中间件
router.use(function firstFunc(req,res,next){
    console.log("Time: ",Date.now());
    next();
});

//若是是根目录
router.get("/",function(req,res){
    res.send("home page");
});

//若是是根目录下的about目录
router.get("/about",function(req,res){
    res.send("about page");
});

//使用路由
//可输入http://127.0.0.1:8000/myRoot获得home page
//可输入http://127.0.0.1:8000/myRoot/about获得about page
//在获得返回的page以前,会先执行firstFunc函数
app.use("/myRoot",router);

//开启站点
app.listen(8000,function(){
    log.info("站点开启")
});

经过路由,能够在返回页面以前,先经过中间件执行若干事物,并且这些中间件是当前路由共享的,这样能够省去许多重复代码,增长代码可利用率的有效性。还能够将Router注册为模块导出,代码更加有可读性。

 

注明:以上学习内容来自:http://www.expressjs.com.cn/guide/routing.html

相关文章
相关标签/搜索