问题
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
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.
回答1:
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.
回答2:
I'm not 100% sure, but if you put all your routes above the :user then a user who registered your pagename would not get displayed.
来源:https://stackoverflow.com/questions/13204513/catch-all-root-level-routing-in-express-js-considerations-and-reserving-possibl