2017-11-25 49 views
5

使用Hapi v17,我只是想制作一个简单的Web API来开始构建我的知识,但每次测试构建的GET方法时都会收到错误。下面是我运行的代码:TypeError:回复不是函数

'use strict'; 
const Hapi = require('hapi'); 
const MySQL = require('mysql'); 

//create a serve with a host and port 

const server = new Hapi.Server({ 
    host: 'serverName', 
    port: 8000 
}); 

const connection = MySQL.createConnection({ 
    host: 'host', 
    user: 'root', 
    password: 'pass', 
    database: 'db' 
}); 

connection.connect(); 

//add the route 
server.route({ 
    method: 'GET', 
    path: '/helloworld', 
    handler: function (request, reply) { 
    return reply('hello world'); 
} 
}); 

server.start((err) => { 
    if (err) { 
     throw err; 
    } 
    console.log('Server running at:', server.info.uri); 
}); 

下面是我收到的错误:我不清楚,为什么有呼叫应答功能的问题

Debug: internal, implementation, error 
    TypeError: reply is not a function 
    at handler (/var/nodeRestful/server.js:26:11) 

,但它是一个致命的现在的错误。

+0

'console.log(reply)'输出的是什么? – 3Dos

+0

@ 3Dos它打印以下内容:“{”statusCode“:500,”error“:”内部服务器错误“,”消息“:”发生内部服务器错误“} – Drew

+0

@MikaelLennholm间距刚好是一条线我相信。错误发生在'return reply('hello world');' – Drew

回答

11

版本哈啤的17具有完全不同的API。

https://hapijs.com/api/17.1.0

路由处理程序是不再通过reply功能作为第二个参数,而不是将它们传递一种叫做Response Toolkit其为含有性能和效用,用于取响应的护理的对象。
有了新的API,你甚至不必使用工具包的响应返回一个简单的文本响应,你的情况,你可以简单地从处理程序返回的文本:

//add the route 
server.route({ 
    method: 'GET', 
    path: '/helloworld', 
    handler: function (request, h) { 
    return 'hello world'; 
    } 
}); 

的响应工具包使用自定义响应,例如设置内容类型。例如:

... 
    handler: function (request, h) { 
    const response = h.response('hello world'); 
    response.type('text/plain'); 
    return response; 
    } 

注:这个新的API,server.start()并不需要一个回调函数,如果你提供一个无论如何也不会被调用(你可能已经注意到,在console.log()你的回调函数永远不会发生)。现在,server.start()返回一个Promise,它可以用来验证服务器是否正常启动。

我相信这个新的API被设计成与async-await语法一起使用。

+1

即使新文档也有错误!我猜他们仍在努力。但是他们至少应该修复Hello World部分,因为新用户无法绕过它。 –

0

看来你在你的代码重复:

const server = new Hapi.Server({ 
    host: 'serverName', 
    port: 8000 
}); 

// Create a server with a host and port 
// This second line is not needed!!! and probably is causing the error 
//you described 
const server = new Hapi.Server(); 
+0

我无意中添加了该行,我在发布之后立即修复了该行。我现在已经更新了这个问题,但在修复之后仍然得到相同的错误 – Drew

0

为了解决这个问题,你只需要与return 'hello world'; 我更换return reply('hello world');是下面的描述:

根据高致病性禽流感v17.x他们有一个新的生命周期方法的接口取代了回复()接口:

  1. 删除了response.hold()和response.resume()。

  2. 方法是异步的,并且所需的返回值是响应。

  3. 响应工具包(h)提供了帮助程序(而不是回复()装饰)。
相关问题