Express.js 的 router.use() 方法
router.use() 方法有一個可選掛載路徑,預設設定為“/”。此方法將對該可選掛載路徑使用指定的中介軟體函式。該方法類似於 app.use()。
語法
router.use( [path], [function, ...] callback )
示例 1
建立一個名為“routerUse.js”的檔案,複製以下程式碼片段。建立檔案後,使用命令“node routerUse.js”執行此程式碼,如下面的示例所示
// router.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;
// If the endpoint not found default is called
router.use(function (req, res, next) {
console.log("Middleware Called");
next();
})
// This method is always invoked
router.use(function (req, res, next) {
console.log("Welcome to Tutorials Point");
res.send("Welcome to Tutorials Point");
})
app.use('/api', router);
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 routerUse.js Server listening on PORT 3000 Middleware Called Welcome to Tutorials Point
示例 2
我們來看看另一個示例。
// router.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;
// All requests will hit this middleware
router.use(function (req, res, next) {
console.log('Method: %s URL: %s Path: %s', req.method, req.url, req.path)
next()
})
// this will only be invoked if the path starts with /v1 from the mount point
router.use('/v1', function (req, res, next) {
console.log("/v1 is called")
next()
})
// always invoked
router.use(function (req, res, next) {
res.send('Welcome to Tutorials Point')
})
app.use('/api', router)
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});使用 GET 請求訪問以下端點 -
- https://:3000/api
- https://:3000/api/v1
輸出
C:\home
ode>> node routerUse.js Server listening on PORT 3000 Method: GET URL: / Path: / Method: GET URL: /v1 Path: /v1 /v1 is called
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP