Node.js -- Router模块中有一个param方法
生活随笔
收集整理的這篇文章主要介紹了
Node.js -- Router模块中有一个param方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
這段時間一直有在看Express框架的API,最近剛看到Router,以下是我認(rèn)為需要注意的地方:
Router模塊中有一個param方法,剛開始看得有點模糊,官網(wǎng)大概是這么描述的:
| 1 | Map logic to route parameters. |
大概意思就是路由參數(shù)的映射邏輯
這個可能一時半會也不明白其作用,尤其是不知道get和param的執(zhí)行順序
再看看源碼里面的介紹:
| 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 |
這就清晰多了,翻譯過來就是說:
在所給的參數(shù)和回調(diào)函數(shù)之間做一個映射,作為使用標(biāo)準(zhǔn)化占位符的路由的前提條件。
下面給出一段具體代碼:
| 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執(zhí)行
轉(zhuǎn)載于:https://www.cnblogs.com/chris-oil/p/4985542.html
總結(jié)
以上是生活随笔為你收集整理的Node.js -- Router模块中有一个param方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到新手表是什么意思
- 下一篇: 梦到和别人打架好不好