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


Express.js app.router()用法及代碼示例

Express.js是一個Node.js Web靈活框架,為移動和Web應用程序提供了一組函數。 Express具有許多開發人員提供的各種方法,其中Express中的一種方法是Router,它用於根據請求將用戶轉移到網站的不同頁麵。

用法:

express.Router([options]);

參數:該函數接受以下參數:

  • caseSensitive:它啟用了區分大小寫函數,這意味著如果路由為“ /contact”(默認情況下)並不意味著它與“ /Contact”,“ /contact”等相同,則忽略大小寫。
  • mergeParams:Express 4.5.0及更高版本具有此函數。如果要通過子路徑從父路徑訪問參數,則需要將mergeParams傳遞為true。
  • strict:它啟用嚴格的路由,這意味著如果路由是“ /about”,則並不意味著它與“ /about /”相同,默認情況下相反。

項目設置和模塊安裝:

步驟1:您可以訪問安裝快速模塊的鏈接。您可以使用此命令安裝此軟件包。



npm install express

步驟2:安裝Express模塊​​後,您可以使用命令在命令提示符下檢查Express版本。

npm version express

步驟3:之後,您可以隻創建一個文件夾並添加一個文件,例如index.js。要運行此文件,您需要運行以下命令。

node index.js

項目結構:如下圖所示。

項目結構

文件名-index.js:

Javascript

// Requiring module 
const express = require('express'); 
const app = express(); 
  
// Port number 
const port = process.env.PORT || 4000; 
  
// import router which is exported 
// in app.js file 
const route = require('./routes/app.js'); 
  
// When a request comes from /result 
// route.It divert to app.js  
app.use('/result', route); 
  
var visit_link = "<a" + " href=" + "/result"
    + 'style="color:green;"'
    + '"text-decoration:none;"'
    + '"text-size:20px" + ">"' 
    + "Hello Geeks" + "</a>" 
    + "<br> <br> Click Hello Geeks"; 
  
// Handling GET Request '/' 
app.get('/', function(req, res) { 
  
    // Sending the html code as a string 
    res.send(visit_link); 
}); 
  
// Server setup 
app.listen(port, function(req, res) { 
    console.log("listen"); 
});

Router() Express中的方法:當您的Web或移動應用程序具有很多路由時,開發人員無法通過將所有路由都保存在一個文件中來保持代碼的可讀性,整潔性,一致性和正確性。因此,快速開發人員提出了一個更好的主意,並引入了一種稱為Router的方法,該方法可以幫助開發人員滿足所有要求。

在此示例項目中,當用戶單擊Hello Geeks時,它將重定向到http://locahost:4000 /result。當請求中包含“ /result”路由時,服務器將運行路由文件夾中的app.js文件。

文件名app.js



Javascript

// Requiring module 
const app = require('express') 
  
// Initiate router 
const router = app.Router(); 
  
// Path Module 
const path = require('path'); 
  
// Handling GET Request 
router.get('/',function(req,res) { 
  res.sendFile(path.dirname(__dirname) 
  + "/index.html") 
}) 
  
// Exporting router variable 
module.exports = router;

文件名-index.html:

完全執行app.js文件後,它將HTML文件發送到該特定路由並在瀏覽器中顯示。

HTML

<!DOCTYPE html> 
<html> 
  
<body> 
    <img style="margin-left:auto; margin-right:auto; 
        display:block;width:50%;" src= 
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-15.png"
        alt="geeksforgeeks" width="500" height="250"> 
</body> 
  
</html>

運行應用程序的步驟:使用以下命令運行index.js文件:

node index.js

輸出:現在打開瀏覽器並轉到http://localhost:4000 /,您將獲得以下輸出。

該項目的工作模式

參考: https://expressjs.com/en/5x/api.html#express.router

相關用法


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