router.param()的參數是名稱和函數。其中name是參數的實際名稱,而function是回調函數。本質上,當用戶路由到該參數時,router.param()函數將觸發回調函數。即使用戶多次路由到該參數,此回調函數也僅在請求響應周期中被調用一次。
用法:
router.param(name, function)
回調函數的參數為:
- req-請求對象
- res-響應對象
- next-下一個中間件函數
- id-的值名稱參數
首先,您需要在節點js應用程序中安裝Express Node模塊。
express js的安裝如下:
npm init npm install express
創建一個名為app.js的文件,並將以下代碼粘貼到該文件中。
//
const express = require("express");
const app = express();
//import router module from route.js file
const userRoutes = require("./route");
app.use("/", userRoutes);
//PORT
const port = process.env.PORT || 8000;
//Starting a server
app.listen(port, () => {
console.log(`app is running at ${port}`);
});
我們必須在同一目錄中創建另一個名為route.js的文件
route.js文件的代碼
const express = require("express");
const router = express.Router();
router.param("userId", (req, res, next, id) => {
console.log("This function will be called first");
next();
});
router.get("/user/:userId", (req, res) => {
console.log("Then this function will be called");
res.end();
});
// Export router
module.exports = router;
通過輸入以下命令來啟動服務器
node app.js
在瀏覽器中輸入以下地址

http://localhost:8000/user/343
您將在終端中看到以下輸出
相關用法
- PHP Ds\Set first()用法及代碼示例
- PHP next()用法及代碼示例
- PHP Ds\Set last()用法及代碼示例
- PHP Ds\Set contains()用法及代碼示例
- p5.js arc()用法及代碼示例
- PHP ord()用法及代碼示例
- d3.js d3.min()用法及代碼示例
- d3.js d3.set.add()用法及代碼示例
- PHP Ds\Map xor()用法及代碼示例
- p5.js value()用法及代碼示例
- PHP Ds\Set add()用法及代碼示例
- p5.js mag()用法及代碼示例
- CSS url()用法及代碼示例
注:本文由純淨天空篩選整理自Malhar_37大神的英文原創作品 Express.js router.param() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。