12

我们正在开发一个 node.js Hapi 服务器,该服务器从 MongoDB 数据库中提取路由列表并设置所述路由以进行服务。这样,由于数据库中的重复路由条目,服务器可能会失败。

我试图查看,但未能找到在 Hapi 中检查重复路线的方法。

是否可以获得 Hapi 服务器当前正在服务的路由列表?

在尝试构建来自 MongoDB 的路由时,我可以进行比标准 try/catch 块更漂亮的错误检查吗?

设置路线的代码如下;请查看我在代码中的注释,了解我需要在哪里处理错误。

MySchema.find({}, function (err, stubs) {
    if (err) {
        console.log('error while loading');
        return;
    }

    for (var i = 0; i < stubs.length; i++) {
        var bodyMessage = stubs[i].body;

        // This is where we can fail, if only I could make a 
        // check for the route here
        server.route({
            method:  stubs[i].method,
            path: stubs[i].path,

            handler: function (request, reply) {
                reply(bodyMessage);
            }
        });
    }

});
4

4 回答 4

22

也许server.table()会帮助你?它返回路由表的副本。来自文档页面的示例:

var table = server.table()
console.log(table);

/*  Output:

    [{
      method: 'get',
      path: '/test/{p}/end',
      settings: {
        handler: [Function],
        method: 'get',
        plugins: {},
        app: {},
        validate: {},
        payload: { output: 'stream' },
        auth: undefined,
        cache: [Object] }
    }] */
于 2014-10-08T16:04:53.587 回答
6

我正在使用 Hapi v17.6.0:

server.table().forEach((route) => console.log(`${route.method}\t${route.path}`));
于 2018-09-26T14:23:01.900 回答
2

我正在使用 Hapi 15.1.1 版,这对我有用:

 // server.select if you have more than one connection
 const table = server.select('api').table();
 let routes = [];
 table[0].table.forEach((route) => { 
   // you can push here the route to routes array
   routes.push(route);
 });
于 2016-10-18T19:59:12.430 回答
1

要修改特定路由,您可以使用连接 obj 中的 .match() 方法按键查找它们。

var routeObj = server.connections[0].match('get', '/example', '<optional host>')
routeObj.settings.handler = function(req, reply){
  reply({"statusCode":404,"error":"Not Found"})
}

如果您有多个连接循环通过它们以更改每个连接。上面将路由处理程序更改为 404,因为您不应该删除路由。

路由存储在由 hapi/node_modules/call 中的路径索引的对象中

于 2017-03-08T15:13:20.233 回答