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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP