Express.js – app.mountpath 属性

所述app.mountpath属性包含在其上安装一个子应用程序的那些路径的模式。子应用程序可以定义为 Express 的一个实例,可用于处理对路由的请求。

这个属性类似于req对象的baseUrl属性;唯一的区别是req.baseUrl返回匹配的 URL 路径而不是匹配的模式。

语法

app.mountpath

示例 1

创建一个文件“appMountpath.js”并复制以下代码片段。创建文件后,使用命令“node appMountpath”运行此代码。

//app.mountpathcode 演示示例

// 导入 express 模块
var express = require('express');

// 初始化 express 和端口号
var app = express();
var user = express(); // 这是一个子应用程序
var PORT = 3000;

// 定义端点
user.get('/', function (req, res) {

   // 打印安装路径
   console.log(user.mountpath);
   res.send('This is the user homepage');
   console.log('This is the user homepage');
});

// 在我们的 mai 应用程序上安装子应用程序
app.use('/user', user); // 挂载子应用
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
输出结果
C:\home\node>> node appMountpath.js
Server listening on PORT 3000
/user
This is the user homepage

示例 2

让我们再看一个例子。

//app.mountpathcode 演示示例

// 导入 express 模块
var express = require('express');

// 初始化 express 和端口号
var app = express();
var PORT = 3000;

// 定义端点
app.get('/', function (req, res) {
   console.log("端点是: ",app.mountpath)
   res.send("Welcome to nhooo.com")
   console.log("Welcome to nhooo.com")
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});
输出结果
C:\home\node>> node appMountpath.js
Server listening on PORT 3000
端点是: /
Welcome to nhooo.com