如何检测无效路由并在hapi js中显示404错误?

时间:2017-06-28 18:28:53

标签: handlebars.js hapijs

我想在用户尝试访问未定义的无效路由时显示404视图页面。例如,如果我试图访问/ myData,那么它应该重定向到/ 404。

server.js

server.route(routes);

routes.js

 module.exports =[
{
  path:'/',
  method:'GET',
  handler:function(request, reply) {
    reply.view('index').unstate('token');
  }
},
{
  path:'/login',
  method:'GET',
  handler:function(request, reply) {
    reply.view('login');
  }
},
{
  path:'/login',
  method:'POST',
  handler:handlers.loginHandler,
  config: {
      state: {
          parse: true, // parse and store in request.state
          failAction: 'error' // may also be 'ignore' or 'log'
      }
  }
},
{
  path:'/register',
  method:'GET',
  handler:function(request, reply) {
    reply.view('register');
  }
}];

1 个答案:

答案 0 :(得分:0)

您可以根据服务器的响应来决定

server.ext({
    type: 'onPreResponse',
    method(request, reply) {
      if (request.response.output.statusCode == 404) {
        //serve your page here
      }
      reply.continue();
    },
 });