Express.js – app.use() 方法
该方法将指定的中间件函数挂载或放置在指定的路径中。仅当请求路径的基址与定义的路径匹配时,才会执行此中间件功能。app.use()
语法
app.use([path], callback, [callback])
参数
path-这是调用中间件函数的路径。路径可以是字符串、路径模式、正则表达式或所有这些的数组。
callback-这些是中间件函数或一系列中间件函数,它们的作用类似于中间件,但这些回调可以调用next(路由)。
示例1
创建一个名为“appUse.js”的文件并复制以下代码片段。创建文件后,使用命令“nodeappUse.js”运行此代码。
//app.use()方法演示示例
//导入express模块
const express = require('express');
//初始化express和端口号
var app = express();
//从express初始化路由器
var router = express.Router();
var PORT = 3000;
//此方法将调用next()中间件
app.use('/api', function (req, res, next) {
console.log('Time for main function: %d', Date.now())
next();
})
//会在中间件之后调用
app.get('/api', function (req, res) {
console.log('Time for middleware function: %d', Date.now())
res.send('Welcome to nhooo.com')
})
//应用程序侦听以下端口
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});现在,使用GET请求点击以下端点
http://localhost:3000/api输出结果
C:\home\node>> node appUse.js Server listening on PORT 3000 Time for main function: 1627490133904 Time for middleware function: 1627490133905
示例2
让我们再看一个例子。
//app.use()方法演示示例
//导入express模块
const express = require('express');
//初始化express和端口号
var app = express();
//从express初始化路由器
var router = express.Router();
var PORT = 3000;
//此方法将调用next()中间件
app.use('/', function (req, res, next) {
console.log('Middleware will not be called')
})
//会在中间件之后调用
app.get('/api', function (req, res) {
console.log('Time for middleware function: %d', Date.now())
res.send('Welcome to nhooo.com')
})
//应用程序侦听以下端口
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});现在,使用GET请求点击以下端点
http://localhost:3000/api输出结果
C:\home\node>> node appUse.js Server listening on PORT 3000 Middleware will not be called
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短