捕获Express.js中的所有根级别路由:注意事项和预留可能的路由以备将来使用? [英] Catch-all root level routing in Express.js: considerations and reserving possible routes for future use?

查看:181
本文介绍了捕获Express.js中的所有根级别路由:注意事项和预留可能的路由以备将来使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express.js(3.0)开发一个Node Web应用程序;我想为这两个用户个人资料提供干净的网址:

I'm using Express.js (3.0) to develop a Node web app; I'd like to have clean URLs for both user profiles:

domain.com/username

以及每个用户创建和共享的页面:

as well as for pages each user creates and shares:

domain.com/username/pagename

我更喜欢干净的网址,使用类似 domain.com/profile/username domain.com/pages/username/pagename

I really prefer the clean URLs to using something like domain.com/profile/username or domain.com/pages/username/pagename.

我们开发的当前路由配置如下所示:

The current route configuration for our development is bootstrapped like so:

app.get('/', content.home);
app.get('/about', content.about);
app.get('/signup', users.signup);
app.get('/login', users.login);
app.get('/:user', users.profile);
app.get('/:user/:userpage', userpage.render);

最后两个是捕获所有路由。现在这样做不错,但我不知道这是不是一个糟糕的设计或实现。

The last two being the catch all routes. Now this works fine, but I'm not sure if it's a bad design or implementation.

更重要的是,我想保留一个或多个页面名称未来的使用,如联系,职业,取消,定价等。我不打算推​​出这些页面,但我想知道是否可以创建一个捕获这些请求的路由文件,将它们发送到占位符页面,而不是将其评估为用户个人资料或用户生成的页面。

More importantly, I'd like to reserve a 100 or so page names for future use, like 'contact', 'careers', 'cancels', 'pricing', etc. I don't plan to launch with these pages, but I'm wondering if I can create a route file that captures these requests and sends them to a placeholder page, rather than them being evaluated as a user profile or user generated page.

我可以明显地防止这些用户名被创建,但是必须成为路由的创新方法,并且在使用全部根级别路由时了解任何其他注意事项 - 由于用户和页面查找不存在的对象或页面,这可能会导致数据库容量不稳定。

I can obviously prevent those usernames from being created, but there's got to be a creative approach for the routing as well, and understand any other considerations when using catch-all root level routing-- this can cause an unwieldily amount of DB strain due to the user and page look ups for non-existing objects or pages.

推荐答案

你可以做的是像下面这段代码。这是咖啡脚本,但一般理论是一样的。

What you could do is something like the following snippet of code. It's in coffee-script, but the general theory is the same.

placeholder = (req, res, next) ->
  res.render 'placeholder'

reserved = ['/contact','/careers','/cancels','/pricing']

each page in reserved
  app.get page, placeholder

app.get '/:user', ....

如果您决定要添加一个额外的占位符页面,只需将其添加到该阵列中并重新启动应用程序。

If you decide you want to add an extra placeholder page, just add it into that array and restart the application.

这篇关于捕获Express.js中的所有根级别路由:注意事项和预留可能的路由以备将来使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆