最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin15浏览0评论

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

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

我正在尝试使用新的HapiJS 17显示页面,但它依赖于http请求。所以基本上我使用了一个rest API,然后将它返回到新的响应工具包又称'h toolkit',但它在控制台中出错

错误:处理程序方法未返回值,承诺或抛出错误

它还会出现浏览器错误

发生内部服务器错误

{"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('')
      .on('data', function(data) {
        return h.response('data:' + data);
      });
  }
});

server.start();

仅供参考,同样的事情在Express中没有任何问题(我猜它也适用于HapiJS 16)

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('')
    .on('data', function(data) {
      res.send('data:' + data);
    });
});

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

我用HapiJS 16找到了这个例子

/

回答如下:

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

请求承诺:https://github/request/request-promise

代码更改为以下内容:

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

评论列表(0)

  1. 暂无评论