如何在hapi中添加路由0.8.4

时间:2015-07-14 16:50:14

标签: javascript node.js hapijs

我对使用nodejs和Hapi启动服务器的这个简单代码有点问题。 这是代码:

var Hapi = require('hapi');

var http = new Hapi.Server('0.0.0.0', 8080);

http.route({
  method: 'GET',
  path: '/api',
  handler: function(request, reply) {
    reply({ 'api' : 'hello!' });
  }
}
);

http.start();

这是错误:

http.route({
     ^
TypeError: undefined is not a function
    at Object.<anonymous> (C:\Users\Prova.js:8:6)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

它&#39;一个非常基本的代码,但我无法理解为什么它与http.route有问题。

1 个答案:

答案 0 :(得分:1)

在hapi 0.8.4中,您可以使用addRoute()添加路线:

var Hapi = require('hapi');

// Create a server with a host and port
var server = new Hapi.Server('localhost', 8000);

// Define the route
var hello = {
    handler: function (request) {

        request.reply({ greeting: 'hello world' });
    }
};

// Add the route
server.addRoute({
    method: 'GET',
    path: '/hello',
    config: hello
});

// Start the server
server.start();

但是那个版本的hapi已经很老了,你应该把它升级到最新版本。目前稳定版的hapi是8.8.0。