Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Express Url Generation

Express Url Generation

Problem

I've recently been playing with nodejs and would like to build my first project with it. But there is a major stumbling block for me.

URL Generation.

I'm very used to Codeigniter's base_url() and site_url(), this gave a full url like http://www.example.com/resources/img/bla.jpg, so it's been a bit odd for me to find that there is no such equivalent functions for NodeJS / Express.

Am I going about this wrong or is there a module somewhere that would make it possible to generate urls much like base_url() and site_url() did?

I'm using the Express Framework with Jade as the template engine and MongoDB as the Database.

Problem courtesy of: Johann du Toit

Solution

The scope of Express and the scope of a PHP framework like Codeigniter are quite different, and Express makes much less assumptions on how your site is laid oud. For example, it would be perfectly possible to serve several virtual hosts with Express (using the connect-vhost middleware). In this case there would be little point in having a function like base_url().

This being said, it would be quite easy to roll your own, something like that:

var BASE_URL = "http://mysite.com"; // Can be loaded in a config file

module.exports.baseUrl = function(path) {
    path = (path || "").replace(/^\//, '');
    return BASE_URL + "/" + path; 
}
Solution courtesy of: Philippe Plantier

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Express Url Generation

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×