Express.js - app.mountpath 屬性


**app.mountpath** 屬性包含掛載子應用程式的路徑模式。子應用程式可以定義為 Express 的一個例項,它可以用來處理對路由的請求。

此屬性類似於 **req** 物件的 **baseUrl** 屬性。唯一的區別是 **req.baseUrl** 返回匹配的 URL 路徑,而不是匹配的模式。

語法

app.mountpath

示例 1

建立一個檔案 **"appMountpath.js"** 並複製以下程式碼段。建立檔案後,使用命令 **"node appMountpath"** 執行此程式碼。

// app.mountpath code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var user = express(); // this is a subapp
var PORT = 3000;

// Defining an endpoint
user.get('/', function (req, res) {

   // printing the mounted path
   console.log(user.mountpath);
   res.send('This is the user homepage');
   console.log('This is the user homepage');
});

// Mounting the subapp over our mai app
app.use('/user', user); // Mounting the sub app
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

C:\home
ode>> node appMountpath.js Server listening on PORT 3000 /user This is the user homepage

示例 2

我們來看看另一個例子。

// app.mountpath code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining an endpoint
app.get('/', function (req, res) {
   console.log("Endpoint is: ",app.mountpath)
   res.send("Welcome to Tutorials Point")
   console.log("Welcome to Tutorials Point")
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

C:\home
ode>> node appMountpath.js Server listening on PORT 3000 Endpoint is: / Welcome to Tutorials Point

更新於: 2021-09-30

405 次瀏覽

開啟您的 職業生涯

完成課程,獲得認證

開始學習
廣告條幅
© . All rights reserved.