ExpressJS,如何路由到我的功能

时间:2014-04-10 04:02:45

标签: javascript node.js express

我是表达JS,nodeJS的新手,希望有些灵魂会在路由方面给我启发。

我在app.js

中有这一行
var core = require('./routes/core/'),
app.get ('/core/:base/:methodfunc', core);

我想要实现的最终结果是当我从URL传入/ core / testmethod / test时,我能够访问testmethod文件中的测试函数

路由:base param是路由到testmethod.js而且:methodfunc方法是testmethod中导出的函数

这是我在/ core中的主要代码 的 index.js

module.exports = function(req, res) {
    var base = req.params.base;
    var methodfunc = req.params.methodfunc;
    var basePage = require('./' + base);

    if (basePage) {
        if (methodfunc) {
            basePage.methodfunc(req, res); //there is something very wrong here
        } else {
            fail();
        }
    } else {
        fail();
    }

    function fail() {
        res.send(404);
    }
}

testmethod.js功能

exports.test = function(req, res) {
    res.json({
        name: 'hello there'
    });
};

谢谢!

1 个答案:

答案 0 :(得分:1)

看起来你想通过名字来调用这个函数,所以它会是:

basePage[methodfunc](req, res);