路由

未匹配的标注

路由

路由用于确定应用程序如何响应用户的请求,包含一个 URI(或路径)和一个特定的 HTTP 请求方法(GET、POST 等)。

基本路由

每个路由可以有一个或多个处理函数,这些函数将在路由被访问时执行。

路由的定义使用以下结构:

app.METHOD(PATH, HANDLER)

其中,appexpress 的实例,METHOD 是该路由的所匹配的请求方法,path 则为该路由匹配的访问路径,HANDLER 是在路由被访问时执行的函数。

例如:

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

该方法定义了一个匹配 GET / 的路由,此时访问 http://localhost:3000/ 将可看到输出 Hello World!

Express 支持的请求方法:getpostputheaddeleteoptionstracecopylockmkcolmovepurgepropfindproppatchunlockreportmkactivitycheckoutmergem-searchnotifysubscribeunsubscribepatchsearchconnect

在定义 m-search 一类的路由时,请使用 app['m-search']('/', function ...

您也可以使用 app.all() 方法来匹配所有的请求方法。

路由路径

路径可以是字符串、字符串模式或正则表达式。

字符串:

app.get('/about', function (req, res) {
  res.send('about');
});

此路由路径将匹配 /about

字符串模式:

app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

此路由路径将匹配 acdabcd

正则表达式:

app.get(/.*fly$/, function(req, res) {
  res.send('/.*fly$/');
});

此路由路径将匹配 butterflydragonfly,但是不匹配 butterflymandragonfly man 等。

路由处理函数

您可以提供多个回调函数,以类似中间件的行为方式来处理请求。唯一例外是这些回调函数可能调用 next('route') 来绕过剩余的路由回调。您可以使用此机制对路由施加先决条件,在不应继续执行当前路由的情况下,可将控制权传递给后续路由。

路由处理程序的形式可以是一个函数、一组函数或者两者的结合,如以下示例中所示。

单个回调函数:

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

多个回调函数:

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

一组回调函数:

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

响应方法

方法 作用
res.download() 将文件发送给用户以下载
res.end() 结束响应进程
res.json() 发送 JSON 响应
res.jsonp() 使用 JSONP 发送 JSON 响应
res.redirect() 重定向请求
res.render() 渲染视图并返回
res.send() 发送各种类型的响应(自动识别类型)
res.sendFile() 以八位元流形式发送文件
res.sendStatus() 设置响应状态码并以响应主体形式发送其字符串表示

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 实例是完整的中间件和路由系统;因此,常常将其称为“微型应用程序”。

以下示例将路由器创建为模块,在其中装入中间件,定义一些路由,然后安装在主应用程序的路径中。

在应用程序目录中创建名为 birds.js 的路由器文件,其中包含以下内容:

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

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('Birds home page');
});
// define the about route
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 中间件函数。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
sunxyw
讨论数量: 0
发起讨论 只看当前版本


暂无话题~