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?
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'.