gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:41 25 4
gpt4 key购买 nike

我有一个在参数数量动态时创建具有多个参数的路由的概念,例如:

/v2/ModuleName/Method/Method2/

在 Express 中,我想将其解析为: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

“我是root”

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

“我是v2”

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

关于node.js - Express.js 中的路由 - 参数的动态数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20869368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com