當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Express.js app.use()用法及代碼示例

app.use()函數用於在指定的路徑上安裝指定的中間件函數。它主要用於為您的應用程序設置中間件。

用法:

app.use(path, callback)

參數:

  1. path:這是調用中間件函數的路徑。它可以是表示路徑或路徑模式或正則表達式模式以匹配路徑的字符串。
  2. callback:它是中間件函數或一係列中間件函數。

快遞模塊的安裝:

  1. 您可以訪問安裝Express模塊​​的鏈接。您可以使用此命令安裝此軟件包。
    npm install express
  2. 安裝Express模塊​​後,可以使用命令在命令提示符下檢查Express版本。
    npm version express
  3. 之後,您可以僅創建一個文件夾並添加一個文件,例如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); 
});

運行程序的步驟:

  1. 項目結構將如下所示:
  2. 確保使用以下命令安裝了Express模塊​​:
    npm install express
  3. 使用以下命令運行index.js文件:
    node index.js

    輸出:

    Server listening on PORT 3000
    
  4. 現在打開瀏覽器並轉到http://localhost:3000 /user,您可以在控製台上看到以下輸出,如下所示:
    Server listening on PORT 3000
    Middleware called
    /user request called
    

    在瀏覽器上,您將看到“歡迎使用GeeksforGeeks”。

相關用法


注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js | app.use() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。