使用redis和hapi构建api

kfgdxczn  于 2021-06-10  发布在  Redis
关注(0)|答案(1)|浏览(266)

我试图通过hapi发送redis的get结果,但我一直得到500。如何将redis get的结果发送到客户端。下面是代码和错误。
错误
调试:内部、实现、错误
错误:处理程序方法未返回值、承诺或引发错误

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

代码

'use strict';
const Hapi = require('@hapi/hapi');
const redis = require("redis");
const client = redis.createClient();

client.on("error", function (error) {
  console.error(error);
});

const init = async () => {

  const server = Hapi.server({
    port: 3001,
    host: 'localhost'
  });

  server.route({
    method: 'GET',
    path: '/api/v1/key/{id}',
    handler: (request, h) => {
      client.get(request.params.id, (err, res) => {
        if (err) {
          h.response(err)
        } else {
          h.response(res)
        }
      });
    }
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {

  console.log(err);
  process.exit(1);
});

init();
64jmpszr

64jmpszr1#

我想出来了。您可以将redis模块转换为promise并从中返回值。

'use strict';
const Hapi = require('@hapi/hapi');
const redis = require('redis');
const client = redis.createClient();
const { promisify } = require("util");
const getAsync = promisify(client.get).bind(client);
const setAsync = promisify(client.set).bind(client);

client.on("error", function (error) {
    console.error(error);
});

const init = async () => {

    const server = Hapi.server({
        port: 5000,
        host: 'localhost'
    });

    server.route({
        method: 'GET',
        path: '/api/v1/key/{id}',
        handler: (req, h) => {
            return getAsync(req.params.id).then(res => {
                console.log(res)
                return res
            }).catch(err => {
                console.error(err)
                return err
            });
        }

    })

    server.route({
        method: 'post',
        path: '/api/v1/key',
        handler: (req, h) => {
            return setAsync(req.payload.hash, req.payload.key).then(res => {
                console.log(res)
                return res
            }).catch(err => {
                console.error(err)
                return err
            })
        }

    })

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();

相关问题