當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Express.js req.app用法及代碼示例

req.app屬性保存對使用中間件的Express應用程序實例的引用。

用法:

req.app

參數:沒有參數。

返回值:Object

快遞模塊的安裝:



  1. 您可以訪問安裝Express模塊​​的鏈接。您可以使用此命令安裝此軟件包。
    npm install express
  2. 安裝Express模塊​​後,可以使用命令在命令提示符下檢查Express版本。
    npm version express
  3. 之後,您可以僅創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。
    node index.js

範例1: 文件名:index.js

var express = require('express'); 
var app = express();  
var PORT = 3000; 
  
app.get('/', function (req, res) { 
  console.log(req.app); 
  res.send(); 
}); 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
});

運行程序的步驟:

  1. 項目結構將如下所示:
  2. 確保使用以下命令安裝了Express模塊​​:
    npm install express
  3. 使用以下命令運行index.js文件:
    node index.js

    輸出:

    Server listening on PORT 3000
    
  4. 現在打開瀏覽器並轉到http://localhost:3000 /,現在您可以在控製台上看到以下輸出:
    Server listening on PORT 3000
    { [EventEmitter:app]
      _events:[Object:null prototype] 
        { mount:[Function:onmount] },
      _eventsCount:1,
      _maxListeners:undefined,
      setMaxListeners:[Function:setMaxListeners],
      getMaxListeners:[Function:getMaxListeners],
      . . .
     _router:
       { [Function:router]
         params:{},
         _params:[],
         caseSensitive:false,
         mergeParams:undefined,
         strict:false,
         stack:[ [Layer], [Layer], [Layer] ] } }
    

範例2: 文件名:index.js

var express = require('express'); 
var app = express();  
var PORT = 3000; 
   
app.get('/user', function (req, res) { 
  console.log(req.app._eventsCount); 
  res.send(); 
}); 
   
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
});

使用以下命令運行index.js文件:

node index.js

輸出:
現在打開瀏覽器,並向http://localhost:3000 /user發出GET請求,現在您可以在控製台上看到以下輸出:

Server listening on PORT 3000
1

參考: https://expressjs.com/en/4x/api.html#req.path




相關用法


注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Express.js req.app Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。