router.use()函數使用指定的一個或多個中間件函數。它本質上為特定路由器所服務的路由安裝中間件。
用法:
router.use( path, function )
參數:
- Path:這是通往該中間件的路徑,就像我們可以擁有/user一樣,現在對於擁有該路由器/user的所有API都將調用該中間件。
- function:該函數傳遞一個回調,當在此路由器中調用指定的路徑時將調用該回調。
快遞模塊的安裝:
- 您可以訪問安裝Express模塊的鏈接。您可以使用此命令安裝此軟件包。
npm install express
- 安裝Express模塊後,可以使用命令在命令提示符下檢查Express版本。
npm version express
- 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
node index.js
文件名:index.js
var express = require('express');
var app = express();
var router = express.Router();
var PORT = 3000;
// All requests to this router will
// first hit this middleware
router.use(function (req, res, next) {
console.log("Middleware Called");
next();
})
// Always invoked
router.use(function (req, res, next) {
res.send("Greetings from GeeksforGeeks");
})
app.use('/user', router);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
運行程序的步驟:
- 項目結構將如下所示:
- 確保使用以下命令安裝了Express模塊:
npm install express
- 使用以下命令運行index.js文件:
node index.js
輸出:
Server listening on PORT 3000
- 現在打開瀏覽器並轉到http://localhost:3000 /user,您可以在屏幕上看到以下輸出:
Server listening on PORT 3000 Middleware Called
您將在瀏覽器中看到以下輸出:
Greetings from GeeksforGeeks
相關用法
- p5.js box()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- PHP max( )用法及代碼示例
- p5.js nf()用法及代碼示例
- p5.js nfc()用法及代碼示例
- PHP each()用法及代碼示例
- CSS url()用法及代碼示例
- p5.js nfp()用法及代碼示例
- PHP end()用法及代碼示例
- PHP key()用法及代碼示例
- PHP pos()用法及代碼示例
- CSS var()用法及代碼示例
- d3.js d3.hsl()用法及代碼示例
注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js | router.use() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。