Express.js中的路由 - 动态参数数量

时间:2014-01-01 14:00:02

标签: node.js express

我创建了一个带有多个参数的创建路由的概念,当它的数量是动态的时,例如:

/v2/ModuleName/Method/Method2/

在Express中,我想将其解析为:Modules.v2.ModuleName.Method.Method2()。何时只是一种方法,这当然应该是Modules.v2.ModuleName.Method()。有可能这样做吗?

1 个答案:

答案 0 :(得分:5)

您可以拆分路径名,然后从Modules对象中查找方法,如下所示:

// fields = ['v2', 'ModuleName', 'Method', 'Method2']

var method = Modules;
fields.forEach(function (field) {
    method = method[field];
})

// call method
console.log(method());

完整代码:

var express = require('express'), url = require('url');
var app = express();

Modules = {
    method: function () { return 'I am root'},
    v2: {
        method: function () { return 'I am v2';}
    }
};

app.get('/callmethod/*', function (req, res) {
    var path = url.parse(req.url).pathname;

    // split and remove empty element;
    path = path.split('/').filter(function (e) {
        return e.length > 0;
    });

    // remove the first component 'callmethod'
    path = path.slice(1);

    // lookup method in Modules:
    var method = Modules;
    path.forEach(function (field) {
        method = method[field];
    })

    console.log(method());
    res.send(method());

});

app.listen(3000);

在浏览器上测试:

http://example.com:3000/callmethod/method

“我是根”

http://example.com:3000/callmethod/v2/method

“我是v2”

PS:你可以改进这个应用程序以支持通过url将params传递给方法:  http://example.com:3000/callmethod/v2/method?param1=hello&param2=word