目錄
1. 目錄結構
2. 代碼實現
2.1 安裝Express
2.2 app.js - 主文件
2.3 globalMiddleware.js - 全局中間件
3. 程序運行結果
4. 總結
在Node.js的Express框架中,全局生效的中間件是指應用程序啟動后,對所有請求都有效的中間件。它通常用于日志記錄、權限驗證、請求解析等場景。下面我們通過代碼示例來詳細介紹如何實現全局生效的中間件。
1. 目錄結構
/your-project├── app.js # 主文件,啟動應用├── middleware│ └── globalMiddleware.js # 全局生效的中間件└── package.json # 項目依賴管理文件
2. 代碼實現
2.1 安裝Express
如果你還沒有安裝Express,請先執行以下命令安裝:
npm init -y
npm install express
2.2 app.js
- 主文件
app.js
是應用的主入口,我們將在這里引入全局中間件并注冊路由。
// app.js
const express = require('express');
const app = express();// 引入全局中間件
const globalMiddleware = require('./middleware/globalMiddleware');// 使用全局中間件
app.use(globalMiddleware);// 定義一些測試路由
app.get('/', (req, res) => {res.send('<h1>Welcome to the Home Page</h1>');
});app.get('/about', (req, res) => {res.send('<h1>Welcome to the About Page</h1>');
});// 監聽端口
const PORT = 3000;
app.listen(PORT, () => {console.log(`Server is running on http://localhost:${PORT}`);
});
說明:
-
通過
app.use(globalMiddleware)
注冊全局中間件,使得所有請求都會先經過該中間件。
2.3 globalMiddleware.js
- 全局中間件
globalMiddleware.js
定義了一個全局生效的中間件,它會記錄請求的時間、方法和訪問的URL。
// middleware/globalMiddleware.js
const globalMiddleware = (req, res, next) => {console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);next(); // 繼續執行下一個中間件或路由
};module.exports = globalMiddleware;
說明:
-
這個中間件會在每個請求到達路由之前被調用。
-
new Date().toISOString()
用于記錄請求時間,req.method
記錄請求方式,req.url
記錄訪問的路徑。 -
next()
用于繼續傳遞請求,否則請求會一直停留在這個中間件里。
3. 程序運行結果
啟動應用:
node app.js
然后訪問以下地址:
-
訪問
http://localhost:3000/
時,終端輸出:[2025-04-01T12:00:00.000Z] GET /
頁面顯示:
<h1>Welcome to the Home Page</h1>
-
訪問
http://localhost:3000/about
時,終端輸出:[2025-04-01T12:00:05.000Z] GET /about
頁面顯示:
<h1>Welcome to the About Page</h1>
4. 總結
-
全局中間件適用于所有請求,不需要在每個路由單獨調用。
-
通過
app.use(middleware)
可以注冊全局中間件,所有請求都會先經過這個中間件。 -
本示例中的全局中間件用于記錄請求日志,但它也可以用于權限驗證、請求體解析等更多場景。
希望本教程能幫助你理解Node.js的全局中間件!
?