Search code examples
javascriptnode.jsexpressurl-mapping

Send URL string to other script with Node.js


I am starting to learn Node.js, using Express with Jade and Mongoose as my default toolbox. I used to develop in PHP, migrated to Python, and learned MVC through Django. Having a large client-side JS game and some inspiration from Mozilla.org, I am willing to make a multiplayer game -- and saw this as a noncommercial opportunity to learn Node: I can take my time with it.

However, I ran into a problem. I'm not trying to write an MVC system on my own, just to separate my site's "apps" like most MVCs do. The question is probably basic -- having this chunk of code:

app.get(/^blog/, function(req, res) {
    require("./blog")();
});

... I understand the basics of Node/Express' URL masking, however I need to pass the rest of the URL string (everything that's after mysite.com/blog) to another URL parsing script, inside the blogapp.

I googled around for a while and couldn't find a good solution. I even found a full tutorial on building an MVC scheme in Node and Express written for an older Express version, but that's a bit over the top for now. Can you provide me a simple solution?

I think blog/index.js should look something like this:

module.exports = function(urlstring) {
    if(urlstring.indexOf('post') != -1) {
        // do stuff...
    }
    else if(urlstring === '/') {
        // return home.jade or something
    }
};

I hope I'm being clear. Thanks in advance!


Solution

  • With express there is no need to parse your URLs on your own. I guess you'll want to build your blog URLs somehow like this

    /blog Show a list of blog posts /blog/post/1 Show blog post with id '1'

    With express 4 you can set up a router for your blog path or a mounted app. Mounted apps allow you to let an app handle all sub URLs of a base URL path. See the express documentation for more detail.

    I'd like to demonstrate how you can use the express 4 router together with the mounting feature of express to build blog routes.

    // Set up express app
    var app = express();
    
    // Set up  a router
    var router = express.Router();
    
    router.get('/', function(req, res) {
      // Show a list of blog posts
    }
    
    router.get('/post/:id', function(req, res) {
      // Show a single blog post 
    }
    
    // Mount router
    app.use('/blog', router);
    

    A benefit of this solution is that your routes registered in the router always get relative URLs with out the /blog prefix so you may reuse your blog routes in some other project under a URL like /companyblog.