1

我正在将 Hapi.js 用于一个项目,当我调用我的路由时,我传递给我的处理程序的配置变量出现未定义。我究竟做错了什么?

服务器.js

var Hapi = require('hapi');
var server = new Hapi.Server('0.0.0.0', 8080);

// passing this all the way to the handler
var config = {'number': 1};

var routes = require('./routes')(config);
server.route(routes);

server.start();

路由.js

var Home = require('../controllers/home');

module.exports = function(config) {
    var home = new Home(config);
    var routes = [{
        method: 'GET',
        path: '/',
        handler: home.index
    }];
    return routes;
}

控制器/home.js

var Home = function(config) {
    this.config = config;
}

Home.prototype.index = function(request, reply) {

    // localhost:8080
    // I expected this to output {'number':1} but it shows undefined
    console.log(this.config); 

    reply();
}

module.exports = Home;
4

1 回答 1

4

The issue is with the ownership of this. The value of this within any given function call is determined by how the function is called not where the function is defined. In your case above this was referring to the global this object.

You can read more on that here: What does "this" mean?

In short the solution to the problem is to change routes.js to the following:

var Home = require('../controllers/home');

module.exports = function(config) {
    var home = new Home(config);
    var routes = [{
        method: 'GET',
        path: '/',
        handler: function(request, reply){
            home.index(request, reply);
        }
    }];
    return routes;
}

I've tested this and it works as expected. On a side note, you're missing out on a lot of hapi functionality by structuring your code in this way, I generally use plugins to register routes instead of requiring all routes as modules and using server.route().

See this project, feel free to open an issue if you have further questions on this: https://github.com/johnbrett/hapi-level-sample

于 2014-11-01T16:14:16.293 回答