Express基础了解—路由

主要是根据官方文档和网上资料整理的。

路由的定义由如下结构组成:

app.METHOD(PATH, HANDLER)。

其中,app 是一个 express 实例;METHOD 是某个 HTTP 请求方式中的一个;PATH 是服务器端的路径;HANDLER 是当路由匹配到时需要执行的函数。

简单实例:

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

路由路径:

路由路径和起起伏伏一起定义了请求的端点,它可以是字符串、字符串模式或者正则表达式。

# 1.使用字符串的路径路由
//匹配根路径的请求
app.get('/', function (req, res) {
  res.send('root');
});

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

# 2.使用字符串模式的路由路径
// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});

# 3.使用正则表达式的路由路径
// 匹配任何路径中含有 a 的路径:
app.get(/a/, function(req, res) {
  res.send('/a/');
});

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

路由句柄:

可以为请求提供多个回调函数,其行为类似中间件。

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

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

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

app.get('/example/a', function (req, res) {
  res.send('Hello from A!');
});
使用多个回调函数处理路由(记得指定 next 对象):

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

app.route():

可使用 app.route() 创建路由路径的链式路由句柄。由于路径在一个地方指定,这样做有助于创建模块化的路由,而且减少了代码冗余和拼写错误。

下面这个示例程序使用 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');
  });

express.Router:

可以使用express.Router类创建模块化、可挂载的路由句柄。(也就是相对于一个公共模块,各个程序都可以进行调用使用)。

Router 实例是一个完整的中间件和路由系统,因此常称其为一个 “mini-app”。

下面的实例程序创建了一个路由模块,并加载了一个中间件,定义了一些路由,并且将它们挂载至应用的路径上。

实例1:

var express = require('express');

// 路由中间件
var router = express.Router();

router.get('/',function (req,res,next) {
    res.send('root');
})

// 路由中间件 导出
module.exports = router;

路由中间件的使用:

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

// 引入 路由中间件
var indexRouter = require('./test3')

// 路由中间件的使用
app.use('/',indexRouter);

app.listen(3000);
console.log('Listen to port 3000');

实例2:

var express = require('express');
var router = express.Router();

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// 定义网站主页的路由
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// 定义 about 页面的路由
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

然后再应用中加载路由模块:

var birds = require('./birds');
...
app.use('/birds', birds);

应用即可处理发自 /birds 和 /birds/about 的请求,并且调用为该路由指定的 timeLog 中间件。

app.get() 和 app.use() :

参考文章:https://blog.csdn.net/wthfeng/article/details/53366169

结论:

  • app.use(path,callback)中的callback既可以是router对象又可以是函数
  • app.get(path,callback)中的callback只能是函数

index.js


var express = require('express');
var router = express.Router();

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

module.exports = router;

app.js

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

var index = require('./routes/index');

//1
app.use('/test1',function(req,res,next){
    res.send('hello test1');

});

//2
app.get('/test2',function(req,res,next){
    res.send('hello test2');

});

//3
app.get('/test3',index);

//4
app.use('/test4',index);

index是一个路由对象,结果,例1、2、4结果都能正确显示,而例3却报404。这说明,给app.get(app.post、app.put同理)赋个路由对象是不行的。

其实,可以将app.get()看作app.use的特定请求(get)的简要写法。即:

var express = require('express');
var app = express();
app.get('/hello',function(req,res,next){
    res.send('hello test2');

});

等同于:

var express = require('express');
var app = express();
var router = express.Router();

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

那么,什么时用app.use(),什么时用app.get()呢?

路由规则是app.use(path,router)定义的,router代表一个由express.Router()创建的对象,在路由对象中可定义多个路由规则。可是如果我们的路由只有一条规则时,可直接接一个回调作为简写,也可直接使用app.get或app.post方法。即

当一个路径有多个匹配规则时,使用app.use,否则使用相应的app.method(get、post)。可以参考express.Router的用法。

# 1. 定义多个路径匹配规则
var express = require('express');
var router = express.Router();

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// 定义网站主页的路由
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// 定义 about 页面的路由
router.get('/about', function(req, res) {
  res.send('About birds');
});

module.exports = router;

# 2. 使用require,就可以使用导出的模块,然后使用app.use()调用。
var birds = require('./birds');
...
app.use('/birds', birds);

关于app.get()和route.get()区别可以参考:https://segmentfault.com/q/1010000008112982

猜你喜欢

转载自blog.csdn.net/u014465934/article/details/81204924