Hapi在处理程序中显示未定义的变量

Hapi在处理程序中显示未定义的变量

本文介绍了Hapi在处理程序中显示未定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Hapi.js用于一个项目,当我调用路由时,传递给我的处理程序的配置变量显示为 undefined .我在做什么错了?

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;

推荐答案

问题出在 this 的所有权上.任何给定函数调用中的 this 的值取决于函数的调用方式,而不是定义函数的位置.在您上面的情况中, this 指的是全局 this 对象.

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.

您可以在此处了解更多信息:什么是"this"?是什么意思?

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

简而言之,解决该问题的方法是将route.js更改为以下内容:

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

我已经对此进行了测试,并且可以正常工作.附带说明一下,通过以这种方式构造代码,您会错过很多hapi功能,我通常使用插件来注册路由,而不是将所有路由都作为模块并使用 server.route().

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

查看该项目,如果对此有其他疑问,请随时提出问题: https://github.com/johnbrett/hapi-level-sample

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

这篇关于Hapi在处理程序中显示未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 12:22