【问题标题】:Why is my node event callback showing up in the event as undefined?为什么我的节点事件回调在事件中显示为未定义?
【发布时间】:2015-08-05 19:07:14
【问题描述】:

我正在尝试将 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;

下面是 eventHandler 代码。
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);

【问题讨论】:

    标签: javascript node.js url dom-events


    【解决方案1】:

    看起来你正在吞下错误。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多