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

二.高级部分

待续…

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值