Hapi error: handler method did not return a value, a promise, or thrown an error

Hapi error: handler method did not return a value, a promise, or thrown an error

我有一个在版本 17 上使用 Hapi 的 NodeJS 应用程序,该应用程序使用 returns 地图图像的 Web 服务,但是,当 运行 下面的代码时,我收到以下错误:

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

var Hapi = require('hapi'),
server = new Hapi.Server({
    host: '0.0.0.0',
    port: 8080,
    routes: {
        cors: true
    },
    SphericalMercator = require('sphericalmercator'),
    sm = new SphericalMercator({ size: 256 }),
    prequest = require('request').defaults({ encoding = null });

var wmsUrl = "http://localhost:8088/service/wms?SERVICE=WMS&REQUEST=GetMap&VERSION=1.1.1&STYLES=&FORMAT=image%2Fpng&HEIGHT=383&WIDTH=768&SRS=EPSG%3A3857";

server.route({
    method: 'GET',
    path: '/{layers}/{z}/{x}/{y}.png',
    handler: async (request, h) => {
        var bbox = sm.bbox(request.params., request.params.y, request.params.z, false, '00000');
        var theUrl = `${wmsUrl}&BBOX=${bbox.join(',')}&LAYERS=${decodeURIComponent(request.params.layers)}`;
        prequest.get(theUrl, function (err, res, body) {
            h.response(body).header('Cache-Control'), 'public, max-age=2629000').header('Content-Type', 'image/png');
        });
    }
});

server.start();

我做错了什么?

我在 phone 中写这篇文章,因为我现在正在使用的 PC 无法访问互联网,如果我因为自动更正器而遗漏或拼错了任何内容,请随时指出我会对其进行编辑以更正它。

如果您查看生命周期方法的 hapi docs,它指出:

Each lifecycle method must return a value or a promise that resolves into a value.

因此,只需 return 处理程序中的内容:

 handler: async (request, h) => {
        var bbox = sm.bbox(request.params., request.params.y, request.params.z, false, '00000');
        var theUrl = `${wmsUrl}&BBOX=${bbox.join(',')}&LAYERS=${decodeURIComponent(request.params.layers)}`;
        prequest.get(theUrl, function (err, res, body) {
            h.response(body).header('Cache-Control'), 'public, max-age=2629000').header('Content-Type', 'image/png');
        });

        return null; // or a Plain Value: string, number, boolean. Could be a Promise etc, more on the link above.
    }

如果你不return任何它不喜欢的东西,它将是未定义的。

编辑:

如果你想 return 来自预请求的 body 结果,你可以将它包装在 Promise 中,然后 return 它:

handler: async (request, h) => {
    ...

    const promise = new Promise((resolve, reject) => {
        prequest.get(theUrl, function (err, res, body) {
            if (err) {
                reject(err);
            } else {
                const response = h.response(body)
                    .header('Cache-Control', 'public, max-age=2629000')
                    .header('Content-Type', 'image/png');

                resolve(response);
            }

        });
    });

    return promise;
}