app.use()函數用於在指定的路徑上安裝指定的中間件函數。它主要用於為您的應用程序設置中間件。
用法:
app.use(path, callback)
參數:
- path:這是調用中間件函數的路徑。它可以是表示路徑或路徑模式或正則表達式模式以匹配路徑的字符串。
- callback:它是中間件函數或一係列中間件函數。
快遞模塊的安裝:
- 您可以訪問安裝Express模塊的鏈接。您可以使用此命令安裝此軟件包。
npm install express
- 安裝Express模塊後,可以使用命令在命令提示符下檢查Express版本。
npm version express
- 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
node index.js
文件名:index.js
var express = require('express');
var app = express();
var PORT = 3000;
// This middleware will not allow the
// request to go beyond it
app.use(function (req, res, next) {
console.log("Middleware called")
next();
});
// Requests will never reach this route
app.get('/user', function (req, res) {
console.log("/user request called");
res.send('Welcome to GeeksforGeeks');
});
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 /user request called
在瀏覽器上,您將看到“歡迎使用GeeksforGeeks”。
相關用法
- PHP pow( )用法及代碼示例
- CSS var()用法及代碼示例
- PHP dir()用法及代碼示例
- p5.js int()用法及代碼示例
- PHP pos()用法及代碼示例
- p5.js sin()用法及代碼示例
- PHP ord()用法及代碼示例
- p5.js tan()用法及代碼示例
- PHP key()用法及代碼示例
- PHP min( )用法及代碼示例
- PHP max( )用法及代碼示例
- p5.js str()用法及代碼示例
- d3.js now()用法及代碼示例
注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js | app.use() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。