如何在 hapi.js 中对路由处理程序进行分组
How do I group route handlers in hapi.js
在我的 hapi.js 应用程序中,我为一组路由创建了一个插件。该插件包含用于定义路由的索引文件和用于定义处理程序的控制器文件。以下代码是应用程序的起点。
index.js
exports.register = function (server, options, next) {
server.route({
method: 'GET',
path: '/coins',
handler: require('./getCoins')
});
next();
};
getCoins.js
module.exports = function (request, reply) {
reply('get all coins called');
};
这按预期工作。当我尝试将多个处理程序合并到一个文件中时,问题就出现了。两个文件(index.js
、controller.js
)中的违规代码如下:
index.js
var controller = require('./controller.js');
exports.register = function (server, options, next) {
server.route({
method: 'GET',
path: '/coins',
handler: controller.getAllCoins()
});
server.route({
method: 'POST',
path: '/coins',
handler: controller.createCoin()
});
next();
};
controller.js
var exports = module.exports = {};
exports.getAllCoins = function (request, reply) {
reply('get all coins called');
};
exports.createCoin = function(request, reply) {
reply('create new coin called');
};
当以这种方式构建我的代码时,我最终得到 ERROR: reply is not a function
。似乎根本没有实例化回复对象。我可以在单独的文件中定义每个处理程序,这会起作用,但如果可以的话,我更愿意将处理程序保留在同一个文件中。我在这里错过了什么?
编辑
添加 console.log(controller);
的内容
{
getAllCoins: [Function],
createCoin: [Function],
getCoin: [Function],
updateCoin: [Function],
deleteCoin: [Function]
}
原来 index.js
文件中的 handler: controller.getAllCoins()
行需要一个命名变量,而不是函数调用。将该行更改为 handler: controller.getAllCoins
解决了这个问题。
在我的 hapi.js 应用程序中,我为一组路由创建了一个插件。该插件包含用于定义路由的索引文件和用于定义处理程序的控制器文件。以下代码是应用程序的起点。
index.js
exports.register = function (server, options, next) {
server.route({
method: 'GET',
path: '/coins',
handler: require('./getCoins')
});
next();
};
getCoins.js
module.exports = function (request, reply) {
reply('get all coins called');
};
这按预期工作。当我尝试将多个处理程序合并到一个文件中时,问题就出现了。两个文件(index.js
、controller.js
)中的违规代码如下:
index.js
var controller = require('./controller.js');
exports.register = function (server, options, next) {
server.route({
method: 'GET',
path: '/coins',
handler: controller.getAllCoins()
});
server.route({
method: 'POST',
path: '/coins',
handler: controller.createCoin()
});
next();
};
controller.js
var exports = module.exports = {};
exports.getAllCoins = function (request, reply) {
reply('get all coins called');
};
exports.createCoin = function(request, reply) {
reply('create new coin called');
};
当以这种方式构建我的代码时,我最终得到 ERROR: reply is not a function
。似乎根本没有实例化回复对象。我可以在单独的文件中定义每个处理程序,这会起作用,但如果可以的话,我更愿意将处理程序保留在同一个文件中。我在这里错过了什么?
编辑
添加 console.log(controller);
{
getAllCoins: [Function],
createCoin: [Function],
getCoin: [Function],
updateCoin: [Function],
deleteCoin: [Function]
}
原来 index.js
文件中的 handler: controller.getAllCoins()
行需要一个命名变量,而不是函数调用。将该行更改为 handler: controller.getAllCoins
解决了这个问题。