我有一个概念,当路由的数量是动态的时,创建具有多个参数的路由,例如:
/v2/ModuleName/Method/Method2/
在快递中,我想将其解析为:Modules.v2.ModuleName.Method.Method2()
.什么时候会只有一种方法,这当然应该Modules.v2.ModuleName.Method()
.可以做到吗?
您可以拆分路径名,然后从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将参数传递给方法: http://example.com:3000/callmethod/v2/method?param1=hello¶m2=word