node.js express 官方Route使用说明

Express路由学习

不记录Express安装配置,只记录具体路由的使用方法。

资料来自于官方:http://expressjs.com/guide/routing.html

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) {
<span style="white-space:pre">	</span>res.send('hello world');
});

首页输出hello world.

Route methods(支持的http方法)

// GET method route
app.get('/', function (req, res) {
<span style="white-space:pre">	</span>res.send('GET request to the homepage');
});
// POST method route
app.post('/', function (req, res) {
<span style="white-space:pre">	</span>res.send('POST request to the homepage');
});

支持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.这些http方法。
// 不区分http method 一切都接收
app.all('/secret', function (req, res, next) {
<span style="white-space:pre">	</span>console.log('Accessing the secret section ...');
<span style="white-space:pre">	</span>next(); // pass control to the next handler
});

Route paths(http路径,类似rewriter或者spring里的控制器,支持正则)

The characters ?, +, *, and () are subsets of their Regular Expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
// will match request to the root
app.get('/', function (req, res) {
<span style="white-space:pre">	</span>res.send('root');
});

// will match requests to /about
app.get('/about', function (req, res) {
<span style="white-space:pre">	</span>res.send('about');
});

// will match request to /random.text
app.get('/random.text', function (req, res) {
 <span style="white-space:pre">	</span>res.send('random.text');
});
// will match acd and abcd
app.get('/ab?cd', function(req, res) {
<span style="white-space:pre">	</span>res.send('ab?cd');
});

// will match abcd, abbcd, abbbcd, and so on
app.get('/ab+cd', function(req, res) {
<span style="white-space:pre">	</span>res.send('ab+cd');
});

// will match abcd, abxcd, abRABDOMcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
<span style="white-space:pre">	</span>res.send('ab*cd');
});

// will match /abe and /abcde
app.get('/ab(cd)?e', function(req, res) {
<span style="white-space:pre">	</span>res.send('ab(cd)?e');
});
// will match anything with an a in the route name:
app.get(/a/, function(req, res) {
<span style="white-space:pre">	</span>res.send('/a/');
});

// will match butterfly, dragonfly; but not butterflyman, dragonfly man, and so on
app.get(/.*fly$/, function(req, res) {
<span style="white-space:pre">	</span>res.send('/.*fly$/');
});

Express uses path-to-regexp for matching the route paths.(Express使用的是path-to-regexp做为正则解析器的)。

Express Route Tester(Express路由测试工具)

Route handlers(路由处理方法)

app.get('/example/a', function (req, res) {
<span style="white-space:pre">	</span>res.send('Hello from A!');
});
找到路由直接输出hello from A!很常规的方式(查询数据,加载模板解析之类)。
app.get('/example/b', function (req, res, next) {
<span style="white-space:pre">	</span>console.log('response will be sent by the next function ...');
<span style="white-space:pre">	</span>next();
}, function (req, res) {
<span style="white-space:pre">	</span>res.send('Hello from B!');
});
交个给下一个回调执行。(不知道为什么要这么支持,没进行过实际项目开发,先理解成node.js机制就是回调回调一直回调,所以Express所实现的callback方法。)
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!');
});
接着又看出了处理器第二个参数支持funciton跟数组传值。
总结下:处理器接收路由(支持正则)并且支持在多个处理器的情况下交给指定的处理器(但处理是顺序执行的)。
原文特意提了一下中间件( middleware,中间件可以做很多事情),使用app.user()或者app.VERB(),我的理解是:中间件就是处理req,res,next时当路由接收时的特定的处理方式(可以是方法,也可以模块。)
从网上找到了一篇文章:








gzip/deflate outgoing responses
可以看出启用了中间件加载了gzip功能,默认输出流启用gzip压缩。
http://www.html-js.com/article/1603 // 另外一篇值得一看
具体的app.user()或者app.VERB()这两个方法,请在 api里面搜索。

Response methods(响应方法)

下面介绍了一些常用的方法。
方法 简介
res.download() Prompt a file to be downloaded.(输出文件下载响应头,也就是http response header 当中的Content-Disposition: attachment; filename=“filename.zip”)
res.end() End the response process.(结束响应过程)
res.json() Send a JSON response.(发送一个JSON响应)
res.jsonp() Send a JSON response with JSONP support.(发送一个JSONP的响应)
res.redirect() Redirect a request.(转向请求地址,默认是传向地址)
res.render() Render a view template.(读取一个模板文件)
res.send() Send a response of various types.(发送一个响应正文,类似常规的Response.Write())
res.sendFile Send a file as an octet stream.(发送一个文件字节流)
res.sendStatus() Set the response status code and send its string representation as the response body.(发送响应状态,比如:200,400,500)
更多的响应对象请参看官方api: http://expressjs.com/4x/api.html#res

app.route(创建路由处理链)

有助于创建 模块化路线,减少冗余和错别字。(类似于 spring里的控制器)
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');
  });
上面是简单的可以匹配request method。
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
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);
载入新的模块。这个
var birds = require('./birds');
只能作用到/birds这一级url目录下。这时会过多来,有可能还是不怎么理解,没关系,我们可以看看这篇文章的第一个实例:
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) {
<span style="white-space:pre">	</span>res.send('hello world');
});
直接使用app.get();这样虽然也可以实现路由功能,但当url路由过多,就会发生路径冗余和错别。
所以最好用路由express.Router()进行模块化操作。


猜你喜欢

转载自blog.csdn.net/ozhangsangong/article/details/45312443