Express.js – app.param() 方法
app.param() 方法主要用于将回调触发器添加到路由参数中,其中 name 表示参数的名称或参数数组,callback 表示回调函数。
语法
app.param([name], callback)
参数
name − 表示必需的参数名称或参数数组。
callback − 表示回调函数。回调函数的参数包括请求对象、响应对象、下一个中间件、参数值以及参数名称,顺序与上面相同。
示例
创建一个名为 "appParam.js" 的文件并复制以下代码段。创建文件后,使用命令 "node appParam.js" 运行此代码。
// app.param() Method Demo Example
// Importing the express module
const express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
app.param('id', function (req, res, next, id) {
console.log('app.param is called');
next();
});
app.get('/api/:id', function (req, res, next) {
console.log('Welcome to Tutorials Point!');
next();
});
app.get('/api/:id', function (req, res) {
console.log('SIMPLY LEARNING');
res.end();
});
// App listening on the below port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 请求访问以下端点
https://:3000/api/21
输出
C:\home
ode>> node appParam.js Server listening on PORT 3000 app.param is called Welcome to Tutorials Point! SIMPLY LEARNING
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP