node学习之express: 路由

一.基础部分

本文使用的express-generator生成的项目

1.路由方法

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, 和 connect。

2.路由使用

在router文件中

var express = require('express');
var router = express.Router();
/*使用属于本路由文件的中间件 */
router.use(function(req, res, next) {
  console.log(`Time: ${new Date()}`);
  next();
});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* POST home page */ 
router.post('/', function(req, res, next) {
  console.log('post');
  // res.json({name: 'syc', value: '1231231'});
  res.send('post request');
});

3.路由路径匹配3中模式

(1)字符串

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

(2)字符串模式

字符 ?、+、* 和 () 是正则表达式的子集,- 和 . 在基于字符串的路径中按照字面值解释。

// 问号是b出现0次或者1次的意思,所以匹配abcd,acd
router.get('/ab?cd', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

(3)正则表达式模式

// 匹配任何路径中含有 a 的路径:
app.get(/a/, function(req, res) {
  res.send('/a/');
});

4.路由中路由句柄(回调函数)

路由句柄可以有多个,即一个路由可以有多个处理函数

function func1(req, res, next) {
  console.log('func1');
  next();
}
function func2(req, res, next) {
  console.log('func2');
  next();
}
function func3(req, res, next) {
  console.log('func3');
  next();
}
router.get('/arr', [func1, func2, func3], function(req, res){
  res.send('经历3个函数完成请求');
});

5.路由响应方法

方法 描述
res.download()
    提示下载文件。
res.end()
    终结响应处理流程。
res.json()
    发送一个 JSON 格式的响应。
res.jsonp()
    发送一个支持 JSONP 的 JSON 格式的响应。
res.redirect()
    重定向请求。
res.render()
    渲染视图模板。
res.send()
    发送各种类型的响应。
res.sendFile
    以八位字节流的形式发送文件。
res.sendStatus()
    设置响应状态代码,并将其以字符串形式作为响应体的一部分发送。

6.注册处理同一个路由上所有方法(get,post,put等)的方法

此方法目前理解应该写到app.js中,后面不知道有没有更好的用法

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

此方法写到某一个路由文件中,功能是拦截此路由文件中所有的路由

/*使用属于本路由文件的中间件 */
router.use(function(req, res, next) {
  console.log(`Time: ${new Date()}`);
  next();
});

二.高级部分

待续…

猜你喜欢

转载自blog.csdn.net/guxiansheng1991/article/details/80900268