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 请求访问以下端点 -

输出

C:\home
ode>> node routerUse.js Server listening on PORT 3000 Method: GET URL: / Path: / Method: GET URL: /v1 Path: /v1 /v1 is called

更新于: 2022-01-29

2K+ 浏览量

启动你的 职业生涯

通过完成课程获取认证

入门
广告
© . All rights reserved.