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

编程入门 行业动态 更新时间:2024-10-25 00:24:18
本文介绍了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().

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

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

更多推荐

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

本文发布于:2023-11-11 10:47:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1578205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   未定义   程序   Hapi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!