Hapi Request 的未解析路径在哪里?

Where is the unresolved path of a Hapi Request?

给定此路由配置:

server.route
method: 'GET'
path: "/app/usage/{id}"
handler: (req, reply) ->
  ...

有没有办法以编程方式从预处理器中的请求对象中获取未解析的路径 /app/usage/{id}?我知道如何获得解析路径,例如/app/usage/1234,但我想要未解析的路径(理想情况下不必使用字符串操作重建它)。

server.ext 'onPreHandler', (request, reply) ->
  resolvedPath = request.path
  unresolvedPath = ?

"unresolved path",我假设你指的是使用 server.route(options)?

创建路由时指定的 path 选项

路由 table 中与请求匹配的路由的条目放置在 request.route 中供您检查:

server.route({
    method: 'GET',
    path: '/app/usage/{id}',
    handler: function (request, reply) {

        const route = request.route;
        const routePath = route.path;  // '/app/usage/{id}'

        reply('hello')
    }
});

它在整个 request lifecycle 中可用,因此您也可以在 onPreHandler 扩展函数中获取它:

server.ext('onPreHandler', function (request, reply) {

    const route = request.route;
    const routePath = route.path;  // Whatever your route path is for the request

    reply.continue();
});

注意 请注意,您无法在 onRequest 扩展函数中查看 request.route.path,因为这是在路由匹配之前调用的。来自 relevant section in the API docs:

  • onRequest extension point
    • request.route is not yet populated at this point.
  • Lookup route using request path
  • ...