2017-11-25 80 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)提供了幫助程序(而不是回覆()裝飾)。