显示来自 HTTP 请求的响应 hapi.js 17.2.0

Display response from HTTP request hapi.js 17.2.0

我正在尝试使用新的 HapiJS 17 显示页面,但它依赖于 http 请求。所以基本上我消耗了休息 API 然后 return 它到新的响应工具包又名 'h toolkit' 但它在控制台中给出错误

Error: handler method did not return a value, a promise, or throw an error

它还会给出一个浏览器错误

An internal server error occurred

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

下面是我的代码(为了简单起见,我试图让它尽可能简单,不处理错误等等)

'use strict';

const Hapi = require('hapi');
const Request = require('request');

const server = Hapi.server({ 
  host: '127.0.0.1', 
  port: 8000,
  router: { stripTrailingSlash: true }
});

//Fix double slash issue
server.ext({
  type: 'onRequest',
  method: function (request, h) {
    var path = request.url.path.replace(/\/\//,'/');
    request.setUrl(path);
    return h.continue;
  }
});

server.route({
  method: 'GET',
  path:'/',
  handler: function (request, h) {
    return h.response('Welcome to HapiJS');
  }
});

server.route({
  method: 'GET',
  path:'/a',
  handler: function(req, h) {
    Request
      .get('https://httpbin.org/ip')
      .on('data', function(data) {
        return h.response('data:' + data);
      });
  }
});

server.start();

FYI, same thing work in Express without any issues (I'm guessing it would work with HapiJS 16 as well

const Express = require('express');
const Request = require('request');
const app = Express();
const port = "8000";

app.get('/', function(req, res, next) {
  res.send('Hello world');
});

app.get('/a', function(req, res, next) {
  Request
    .get('https://httpbin.org/ip')
    .on('data', function(data) {
      res.send('data:' + data);
    });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

我用 HapiJS 16 找到了这个例子

http://www.eloquentwebapp.com/comsume-restful-api/

错误提示您应该 return 像这样 h.response 的承诺:

server.route({
  method: 'GET',
  path:'/a',
  handler: (req, h) =>
    new Promise(
      (resolve,reject)=> 
        Request
        .get('https://httpbin.org/ip')
        .on('data', function(data) {
          resolve(h.response('data:' + data));
        })
    )
});

This only work with Hapi.js 16

但是;根据 documentation 你不需要 return 任何东西并且可以做这样的事情:

server.route({
  method: 'GET',
  path:'/a',
  handler: (req, res) =>
    Request
    .get('https://httpbin.org/ip')
    .on('data', function(data) {
      res('data:' + data);
    })
});

因为,HapiJs v17.x 基于 async/await。 使用 const Request = require('request-promise');

Request-Promise: https://github.com/request/request-promise

代码更改如下:

server.route({
method: 'GET',
path:'/a',
handler: async function(req, h) {
  let response = await Request.get('https://httpbin.org/ip');
  return response;
 }
});