Express.js – app.use() 方法


app.use() 方法在指定路徑掛載或應用指定中介軟體函式。僅當請求路徑的基礎與已定義路徑匹配時,才會執行此中介軟體函式。

語法

app.use([path], callback, [callback])

引數

  • 路徑 − 這是呼叫中介軟體函式的路徑。路徑可以是字串、路徑模式、正則表示式或所有這些的陣列。

  • 回撥 − 這些是中介軟體函式或一系列中介軟體函式,它們的行為類似於中介軟體,不同之處在於這些回撥可以呼叫 next(路由)。

示例 1

建立一個名為 "appUse.js" 的檔案,然後複製以下程式碼片段。建立檔案後,使用命令 "node appUse.js" 來執行此程式碼。

// app.use() 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;

// This method will call the next() middleware
app.use('/api', function (req, res, next) {
   console.log('Time for main function: %d', Date.now())
   next();
})

// Will be called after the middleware
app.get('/api', function (req, res) {
   console.log('Time for middleware function: %d', Date.now())
   res.send('Welcome to Tutorials Point')
})

// 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

輸出

C:\home
ode>> node appUse.js Server listening on PORT 3000 Time for main function: 1627490133904 Time for middleware function: 1627490133905

示例 2

我們來看另一個示例。

// app.use() 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;

// This method will call the next() middleware
app.use('/', function (req, res, next) {
   console.log('Middleware will not be called')
})

// Will be called after the middleware
app.get('/api', function (req, res) {
   console.log('Time for middleware function: %d', Date.now())
   res.send('Welcome to Tutorials Point')
})

// 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

輸出

C:\home
ode>> node appUse.js Server listening on PORT 3000 Middleware will not be called

更新日期:2021-10-01

12K+ 人閱讀

開啟您的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.