我尝试使用新的HapiJS 17显示页面,但它依赖于http请求。所以基本上我使用了一个rest API,然后将它返回给新的响应工具包aka' 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('https://httpbin.org/ip')
.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('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
找到了这个例子答案 0 :(得分:1)
错误表明您应该像这样返回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));
})
)
});
这仅适用于Hapi.js 16
然而;根据{{3}},您不必返回任何内容,可以执行以下操作:
server.route({
method: 'GET',
path:'/a',
handler: (req, res) =>
Request
.get('https://httpbin.org/ip')
.on('data', function(data) {
res('data:' + data);
})
});
答案 1 :(得分:1)
因为,HapiJs v17.x基于async / await。
使用const Request = require('request-promise');
代码更改为以下内容:
server.route({
method: 'GET',
path:'/a',
handler: async function(req, h) {
let response = await Request.get('https://httpbin.org/ip');
return response;
}
});