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?

4

1 回答 1

3

正如我在评论中提到的,我认为您正在寻找一种使用子应用程序(如 Rails 引擎)的方法来模块化您的应用程序。如果是这种情况,您应该使用 app.use() 挂载子应用程序。

这里有一个很好的视频。

视频中未提及的最后一件事是,您可以相对安装子应用程序。例如:

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

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

这会将子应用程序中的路由视为来自“/base”路径。例如,在子应用程序中捕获“/a”的路由,在本示例中挂载时,会将请求匹配到“/base/a”。

于 2013-03-04T22:25:05.373 回答