Hapi showing undefined variable inside handler

ε祈祈猫儿з 提交于 2021-02-11 10:46:31

问题


I'm using Hapi.js for a project and a config variable that I'm passing to my handler is coming up as undefined when I call my route. What am I doing wrong?

server.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();

routes.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;
}

controllers/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;

回答1:


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



来源:https://stackoverflow.com/questions/26686857/hapi-showing-undefined-variable-inside-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!