Node.js學習之路27——Express的router物件

Karuru發表於2019-02-16

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

相關文章