【问题标题】:How to dynamically create an express route once a user inputs the name of the route用户输入路线名称后如何动态创建快速路线
【发布时间】:2021-07-27 10:24:28
【问题描述】:

这很难解释,但是,

我正在创建一个 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 需要写下感谢您签到并显示有多少人签到(访问过该路线)。

抱歉解释得不好,但我想不出任何其他方式来解释

谢谢!

【问题讨论】:

  • 也许你可以考虑使用路由参数比如'/:company_name'或者ajax来查询结果取决于输入值?
  • @HWSiew 完美运行!它会创建路线,并且无论何时输入!非常感谢
  • 计数器到底是什么?
  • 没错,您可以创建数据库条目来跟踪每个供应商签到柜台。

标签: javascript html express routes


【解决方案1】:

您将需要一个数据库来存储所有自定义 URL,即一旦用户进入一个站点,将其存储在数据库中(以及有关用户的其他信息)。

在此示例中,假设您使用 MongoDB(使用 mongoose 库)和 EJS(只是一个示例实现,您不必使用这些)。

当用户发出请求时,您可以将所有请求定向到中间件(如果找到 URL,则发送文件,否则转到默认主页):

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
   }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    相关资源
    最近更新 更多