Express.js - router.param() 方法
router.param(name, callback) 向路由引數添加回調,其中 name 定義引數的名稱,callback 是 **回撥** 函式。
以下是 **callback 函式的引數 -
req - 請求物件
res - 響應物件
next -- 下一個中介軟體
name - name 引數的值
語法
router.param( name, callback )
示例
建立一個名為 "routerParam.js" 的檔案,並複製以下程式碼段。建立檔案後,使用命令 "node routerParam.js" 執行此程式碼,如下例所示 -
// router.param() Method Demo Example
// Importing the express module
var express = require('express');
// Importing the route module
const userRoutes = require("./router");
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Defining the route
app.use("/", userRoutes);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});router.js
// Importing the express module
const express = require("express");
const router = express.Router();
// Defining the router param with its value
router.param("userId", (req, res, next, id) => {
console.log("I am called first");
next();
});
router.get("/user/:userId", (req, res) => {
console.log("I am called next");
res.end();
});
// Export router as a module
module.exports = router;透過 GET 請求訪問以下端點 -
https://:3000/user/21
輸出
C:\home
ode>> node routerParam.js Server listening on PORT 3000 I am called first I am called next
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP