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://127.0.0.1:3000/user/21
输出
C:\home
ode>> node routerParam.js Server listening on PORT 3000 I am called first I am called next
广告