Node.js进修之路27——Express的router对象

Router([options])

let router = express.Router([options]);
  • options对象
  • caseSensitive,大小写敏感,默许不敏感
  • mergeParams,保存父路由器的必须参数值,假如父项和子项具有争执的参数称号,则该子项的值将优先
  • strict,激活严厉路由,默许禁用,禁用以后/uu一般接见,然则/uu/不可以接见

1. router.all

  • 悉数挪用
  • router.all(path, [callback, ...] callback)
router.all('*', fn1, fn2...);
// 或许
router.all('*', fn1);
router.all('*', fn2);
// 或许
router.all('/user', fn3);

2. router.METHOD

  • router.METHOD(path, [callback, ...] callback)
  • 实际上就是ajax的种种要求要领
router.get('/', (req, res, next) => {
    
})

router.post('/', (req, res, next) => {
    
})

3. router.route(path)

var router = express.Router();

router.param('user_id', function(req, res, next, id) {
  // sample user, would actually fetch from DB, etc...
  req.user = {
    id: id,
    name: 'TJ'
  };
  next();
});

router.route('/users/:user_id')
.all(function(req, res, next) {
  // runs for all HTTP verbs first
  // think of it as route specific middleware!
  next();
})
.get(function(req, res, next) {
  res.json(req.user);
})
.put(function(req, res, next) {
  // just an example of maybe updating the user
  req.user.name = req.params.name;
  // save user ... etc
  res.json(req.user);
})
.post(function(req, res, next) {
  next(new Error('not implemented'));
})
.delete(function(req, res, next) {
  next(new Error('not implemented'));
})

4. router.use

4.1 运用路由

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

// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function(req, res, next) {
  console.log('%s %s %s', req.method, req.url, req.path);
  next();
});

// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar', function(req, res, next) {
  // ... maybe some additional /bar logging ...
  next();
});

// always invoked
router.use(function(req, res, next) {
  res.send('Hello World');
});

app.use('/foo', router);

app.listen(3000);

4.2 运用模块要领

var logger = require('morgan');

router.use(logger());
router.use(express.static(__dirname + '/public'));
router.use(function(req, res){
  res.send('Hello');
});
    原文作者:Karuru
    原文地址: https://segmentfault.com/a/1190000013474265
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞