TypeError: reply is not a function

Drew picture Drew · Nov 25, 2017 · Viewed 10.9k times · Source

Using Hapi v17, I am just trying to make a simple web API to start building my knowledge, but I keep getting an error every time I test the GET methods built out. Below is the code I am running:

'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);
});

Below is the error I am getting:

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

I am unsure as to why there is an issue calling the reply function, but it is a fatal error as of right now.

Answer

Lennholm picture Lennholm · Nov 25, 2017

Version 17 of Hapi has a quite different API.

https://hapijs.com/api/17.1.0

Route handlers are no longer passed the reply function as the second argument, instead they are passed something called the Response Toolkit which is an object containing properties and utilities for taking care of the response.
With the new API you don't even have to use the Response Toolkit to return a simple text response as in your case, you can simply return the text from the handler:

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

The Response Toolkit is used to customize the response, such as setting the content type. Ex:

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

Note: with this new API, server.start() doesn't take a callback function and if you provide one anyway it won't get invoked (you may have noticed that the console.log() in your callback function never happen). Now, server.start() returns a Promise instead which can be used to verify that the server started properly.

I believe this new API is designed to be used with async-await syntax.