Express routes - best way to make a url params.id serve static and dynamic content

Problem

Suppose I have a urls like

www.foo.com/abc
www.foo.com/huyr
... etc

where 'abc' and 'huyr' in this example are IDs, and i'd fetch info from the database where the key is that id.

But suppose I also want static links (that'll serve static pages) to follow the same url format:

www.foo.com/about
www.foo.com/contact

What would be the best way to do this?

Right now I have something like this in mind

exports.view = function(req, res) {
    var id = req.params.id
    switch (id) {
        case 'about':
            // load 'about' controller
            break
        case 'contact':
            // load 'contact' controller
            break
        default:
            // proceed with this function
    }

}

Is this the best approach? is there a more efficient/organized way to do this?

Problem courtesy of: sqram

Solution

Best way, in my opinion, would be to serve those pages, static or not, like you would with any other page. Respond to the GET request with the right page.

// will respond to http://www.site.com/about
app.get('/about', function( req, res, next ) {
    res.render('about.ejs'  // etc
});

// will respond to http://www.site.com/contact
app.get('/contact', function (req, res, next) {
    res.render('contact.ejs' // etc
});

// will respond to any first subdir (iirc) http://www.site.com/(?)
app.get('/:id', function ( req, res, next ) {
    var id = req.param['id'];

    // db query, etc
});

You static pages of course can be in a route to make it cleaner. Only thing you need to make sure of is you respond to those static routes before the id route, or else you will be responding to the about/contact url with the route that you want responding to the ids. Order matters here.

Solution courtesy of: Chris

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.