Node.js -- Router模塊中有一個param方法


這段時間一直有在看Express框架的API,最近剛看到Router,以下是我認為需要注意的地方:

Router模塊中有一個param方法,剛開始看得有點模糊,官網大概是這么描述的:

1
Map logic to route parameters.

大概意思就是路由參數的映射邏輯

這個可能一時半會也不明白其作用,尤其是不知道get和param的執行順序

再看看源碼里面的介紹:

1
2
3
Map the given param placeholder `name`(s) to the given callback.
Parameter mapping is used to provide pre-conditions to routes
which use normalized placeholders

這就清晰多了,翻譯過來就是說:

在所給的參數和回調函數之間做一個映射,作為使用標准化占位符的路由的前提條件。

下面給出一段具體代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var  express = require( 'express' );
var  app = express();
var  router = express.Router();
 
router.count = 0;
router.get( '/users/:user' function (req, res, next) {
     router.count ++;
     console.log(router.count);
});
router.param( 'user' function (req, res, next, id) {
     router.count ++;
     res.send({count: router.count});
     next();
});
 
app.use(router);
app.listen(3000);

命令行下輸入

node xxx.js

瀏覽器訪問

http://localhost:3000/users/bsn

這時候命令行會輸出2,而瀏覽器會輸出

{
count: 1
}

因此,param會先於get執行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM