如何在hapi 0.8.4中添加路由

How to add a route in hapi 0.8.4

本文关键字:添加 路由 hapi      更新时间:2023-09-26

我有一个小问题与这个简单的代码启动服务器与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

这是一个非常基础的代码,但我不明白为什么它有http.route的问题。

在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