TypeError:回复不是函数

Dre*_*rew 12 javascript node.js hapi.js

使用Hapi v17,我只是想创建一个简单的Web API来开始构建我的知识,但每次测试构建的GET方法时我都会遇到错误.以下是我正在运行的代码:

'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);
});
Run Code Online (Sandbox Code Playgroud)

以下是我得到的错误:

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

我不确定为什么调用回复函数存在问题,但现在这是一个致命的错误.

Len*_*olm 19

Hapi的第17版有一个完全不同的API.

https://hapijs.com/api/17.1.0

路由处理程序不再reply作为第二个参数传递函数,而是传递一个名为Response Toolkit的东西,它是一个包含用于处理响应的属性和实用程序的对象.
使用新的API,您甚至不必使用Response Toolkit来返回简单的文本响应,就像您的情况一样,您只需从处理程序返回文本:

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

Response Toolkit用于自定义响应,例如设置内容类型.例如:

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

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

我相信这个新API旨在与async-await语法一起使用.

  • 即使是新文档也有错误!我猜他们还在努力.但他们至少应该修复Hello World部分,因为新用户无法绕过它. (2认同)