Johann du Toit
Johann du Toit

Reputation: 2667

Express Url Generation

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.

Upvotes: 1

Views: 915

Answers (1)

Philippe Plantier
Philippe Plantier

Reputation: 8073

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; 
}

Upvotes: 2

Related Questions