1

I'm new in nodejs. I want to build a rest service with multiple, lets say, categories.

> app.js 
var express = require('express')
  , http = require('http')
  , routes = require('./routes')
  , path = require('path');

app = express();
app.use(app.router);

app.get('*',routes.index);

app.listen(3000);
console.log('Express app started on port 3000');

and

> routes/index.js
var sites = [
    'sve',
    'ice'
];

exports.index = function(req,res){
    var url = req.url.split('/');
    for (i in sites) {
        app.get('/' + sites[i] + '/*',require('./' + sites[i]));
    }
};  

and

> routes/sve/index.js
module.exports = function(req, res){
  console.log('sve')
  res.end({category:'sve'});
};

and

> routes/sve/index.js
module.exports = function(req, res){
  console.log('sve')
  res.end({category:'sve'});
};

when I run "node app" I get "Express app started on port 3000" and the server is running but when I access "localhost:3000/sve/test" I have no response or "localhost:3000/ice/test" or even "localhost:3000/abc/test". Not even in the console.

What am I doing wrong?

Martin
  • 5,119
  • 3
  • 18
  • 16
  • I am not quite sure what you are trying to do, but it kind of seems like you are trying to mount sub-applications? So that everything to mydomain.com/ice/* gets handled by a different set of routes specific to ice, etc? – Nick Mitchinson Mar 04 '13 at 22:17
  • Yes, I want to split the application in different sub apps. When /sve/ is detected runs a piece of code, when /ice/ is detected, another piece – Gonçalo Silva Dias Mar 04 '13 at 22:19

1 Answers1

3

As mentioned in my comment, I think you are looking for a method of using sub-apps (like Rails Engines) do modularize your application. If this is the case, you should use app.use() to mount a sub-app.

There's a good video on it here.

One last thing of relevance that isn't mentioned in the video, you can mount sub-apps relative. For instance:

var subapplication = require('./lib/someapp');

app.use('/base', app.use(subapplication));

This will treat the routes in subapplication as being from the '/base' path. For instance, a route catching '/a' in subapplication, when mounted in this example, will match a request to '/base/a'.

Nick Mitchinson
  • 5,452
  • 1
  • 25
  • 31