![](/img/trans.png)
[英]Nodejs - How to route by name in url with express and mongoose?
[英]How to dynamically create an express route once a user inputs the name of the route
這將很難解釋,但是,
我正在創建一個 covid 簽到網站,我希望有人可以選擇以企業主身份登錄並為其業務創建簽到路線。
到目前為止,我可以通過硬編碼企業路線來做到這一點,例如麥當勞路線的代碼如下:
checkInCounter_1 = 0;
router.get('/mcdonalds.html', function(req, res, next) {
checkInCounter_1 ++;
res.send(`
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="header_maccas">
<h1 id="headerCont3">Covid Check-In for McDonalds</h1>
</div>
<h1 id="maccas_thanks">thankyou for checking into McDonalds!</h1>
<p>${checkInCounter_1} total people have checked in.</p>
</body>
</html>
`);
});
但我真的希望企業主能夠在輸入字段中輸入他們的業務,然后它會為他們的業務動態創建一個簽入路線 - 如下所示:
“進入你的企業”:企業主然后輸入沃爾瑪或其他東西,然后創建一條與麥當勞非常相似的路線,除了沃爾瑪。
我需要這個選項,因為我不能只對每家公司進行硬編碼,我希望創建一條 URL 路線,並以企業主輸入的任何名稱命名 -> 在字段中輸入 Walmart 創建 /walmart.html
其中 walmart.html 需要寫下感謝您簽到並顯示有多少人簽到(已訪問該路線)。
抱歉解釋得不好,但我想不出任何其他方式來解釋
謝謝!
您將需要一個數據庫來存儲所有自定義 URL,即一旦用戶進入一個站點,將其存儲在數據庫中(以及有關用戶的其他信息)。
在此示例中,假設您使用 MongoDB(使用 mongoose 庫)和 EJS(只是示例實現,您不必使用這些)。
當用戶發出請求時,您可以將所有請求定向到中間件(如果找到 URL,則發送文件,否則將 go 發送到默認主頁):
app.use(async (req, res, next) => { // Whenever there's a request, it goes through this function
var urlRequested = req.originalUrl; // req.originalUrl is everything after the name of your site. Beware it includes query strings (which can be easily removed with urlRequested.split('?')[0])
// Here, you make a request to the database with urlRequested. If you have a URL that matches, you can send a result with information. It would be helpful to use a templating engine, such as EJS
// Assuming you've connected and setup mongoose and EJS
var isUrl = await nameOfYourMongooseModel.findOne({ storedUrl: urlRequested });
if(isUrl !== null) {
res.render('someEjsFile', { information: isUrl });
} else {
next(); // Go to your default homepage
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.