如何在Hapi js

时间:2018-06-16 02:56:14

标签: javascript server routes hapijs

我试过这个https://github.com/hapijs/hapi/issues/800。这对我没用。

const start = async () => {

    await server.register(require('inert'));

    server.route({
        method: 'GET',
        path: '/samplespa/{file*}',
        handler: function (request, h) {
            directory :{
                path : './samplespa/'
                listing: true
            }
        }
    });

    server.ext('onPostHandler', (request, reply) => {
        console.log('WORD');
        const response = request.response;
        if (response.isBoom && (response.output.statusCode === 500)  ) {
        return reply.file('./samplemap.html');
        }
        return reply.continue;
    });



    await server.start();

    console.log('Server running at:', server.info.uri);
};

start();

我想服务目录samplespa并呈现文件" index.html"在其中并注意index.html是用Angular 1.X编写的,并且依赖于目录中的文件..

同样适用于路径:http://localhost:8000/samplespa/index.html

我得到以下回复

{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}

我在vs代码中收到以下错误信息:

Debug: internal, implementation, error
Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (/Users/pavithran/projects/toilet-tracker/node_modules/hapi/lib/toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

怎么做?我在过去的两天里尝试了所有的东西而且无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

对于单个文件,您可以使用以下代码:

    server.route({
        method: 'GET',
        path: '/samplespa/index.html',
        handler: function (request, h) {
            return h.file('./samplespa/index.html');
        }
    });   

对于多个文件,请执行以下操作。请注意,处理程序现在不是函数,而是对象。

    server.route({
        method: 'GET',
        path: '/samplespa/{file*}',
        handler: {
          directory: {
            path: 'samplespa'
          }
        },
    });