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