hapi.js - 404 route VS static files route

感情迁移 提交于 2019-12-05 00:53:20

You're defining 2 routes with the same method and path, which is a conflict as far as hapi's router is concerned. That's why you're getting the error.

If a file isn't found by the directory handler, it will respond with a 404 error by default.

What you can do is intercept this with an onPreReponse handler, which checks if the response is an error response (a Boom object), and if so respond however you wish. In your case by redirecting to /:

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({ port: 4000 });

server.route([{
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            reply('Welcome home!');
        }
    }, {
        method: 'GET',
        path: '/{p*}',
        handler: {
            directory: {
                path: 'public',
                listing: false
            }
        }
    }
]);

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

    if (request.response.isBoom) {
        // Inspect the response here, perhaps see if it's a 404?
        return reply.redirect('/');
    }

    return reply.continue();
});


server.start(function () {
    console.log('Started server');
});

Recommended reading:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!