我正在尝试将 URL 字符串作为“数据”传递回我的事件处理程序。
我对服务器的请求是“https://172.20.10.6/index.html ”。
正如我所期望的,下面的 console.log
打印出“/index.html”。
switch(req.method) {
case 'GET':
console.log("logged from plugin-https.js: url: " + req.url);
ee.emit("dataIn", req.url);
break;
下面是事件处理程序代码。
console.log(data);
的计算结果为“未定义”。我试图找出这是为什么。这似乎是一个非常简单的直接回调,所以我想知道为什么当数据出现在事件处理代码中时没有定义数据。
plugin = rtrn;
console.log('4');
plugin.dataIn(config, function(err, data) {
if(err, data) {
console.log('error geting data');
} else {
// This is where request events are being handled.
console.log(data);
console.log('We are in the event handling codeblock of funtion startRuntime() located in interactor.js');
另外,这是我的回调代码
var ee = new events.EventEmitter();
function dataIn(config, callback) {
if(typeof callback === 'function') {
ee.on("dataIn", callback);
最佳答案
看来您正在接受错误。
if(err, data) {
console.log('error geting data');
}
该条件(err, data)
将忽略err
的值。如果 data
未定义,它将是假的,并且您不会知道发生了错误。您可能想要更像这样的东西:
if (err) {
console.log('error getting data')
}
追溯到你的发射器,你正在以一种将数据发送到第一个参数的方式发射,这应该是错误发生的地方。所以这个:
ee.emit("dataIn", req.url);
...应该更像这样:
ee.emit("dataIn", null, req.url);
关于javascript - 为什么我的 Node 事件回调在事件中显示为未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419064/