我有一个 ExpressJS 应用程序,其中有api.js
管理连接到 Couchbase 的路由,然后发出内部函数couchbaseConnected
等待的事件。init()
api.js
里面init()
我想推那些exports.someFunction(req, res){return something;}
。但是当我只是将这些导出放入init()
函数中时,我得到了一个错误.get() requires callback functions but got a [object Undefined]
,所以看起来我做错了。
问题是如何从 NodeJS 中的另一个函数导出函数?
这是代码:
//connecting to couchbase and emitting event on connection
couchbase.connect(dbConfiguration, function (err, bucket) {
if (err) {
console.log(err);
}
cb = bucket;
eventEmitter.emit('couchbaseConnected');
});
//listening for the event and fire init() when it's there
eventEmitter.on('couchbaseConnected', function (e) {
console.log('Connected to Couchbase.'.green);
init();
});
function init() {
exports.getUserData = function (req, res) {
if (req.user != undefined && req.user.meta != undefined) {
res.json(200, {result: 'ok'})
}
else {
res.json(401, {error: 'Unauthorized request.'})
}
};
}
这是位于的 ExpressJS .get() app.js
:
app.get('/api/user/data/:type', api.getUserData);