【问题标题】:Switch between JSON / View in onPreResponse in Hapi.js在 Hapi.js 的 onPreResponse 中的 JSON / View 之间切换
【发布时间】:2016-03-20 14:02:30
【问题描述】:

我正在尝试根据 URL 发送响应。想检查是否可以检查 url 并在 onPreResponse 中发送响应。这是我想做的事情。

server.ext('onPreResponse', function (request, reply) {
  if (request.path.indexOf('/api') > -1 ) {
     // Do nothing. Let the response go as JSON
  } else {
     // Send back html by populating json data into 
     // handlebar template
     reply.view('layout', request.response.source);  // Need replacement for this
  }
  reply.continue();
});

如何告诉 HAPI 使用视图进行渲染

【问题讨论】:

  • 为什么必须在onPreResonse 内?有什么理由不使用标准路由功能(即路径为 /api/{path*} 的路由)?
  • 这是个好主意。一个例子将不胜感激。
  • 我需要查看更多代码才能了解您到底想要实现什么。
  • 如果 URL 以 /api 开头或通过 Handlebars 路由结果,我正在尝试发回结果 JSON。我想在 API 和 Web 应用程序之间共享大约 100 种方法。所以本质上,我想说“如果 url 以“/api”开头,那么做“return reply(result)”或 return reply.view('index', request.respose.context)。

标签: javascript json hapijs


【解决方案1】:

如果我正确理解你的问题,你为什么不能定义两条路线?

[{
    method: 'GET',
    path:'/',
    handler: function (request, reply) {
        reply.view('layout', request.response.source);
    }
},
{
    method: ['GET','POST'],
    path:'/api',
    handler: function (request, reply) {
        reply(result);
    }
}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多