2014-09-26 28 views
0

我試圖在使用的NodeJS時EventSource以獲取有關錯誤信息的錯誤獲取信息,我想你可以用下面的例子更好地理解了我:有關使用EventSource的

var url = 'http://api.example.com/resource' 
var EventSource = require('eventsource'); 

var es = new EventSource(url); 
es.onmessage = function(e) { 
    console.log(e.data); 
}; 

es.onerror = function(event) { 
    console.log(event); 
}; 

的onerror功能我想獲得有關錯誤的信息,但event爲空或未定義還有es對象(當然,這只是對象有一對大括號的卡梅斯)。我想讀錯誤情況下的迴應標題,如:

es.onerror = function(e) { 
    console.log(e.header.location); 
}; 

這可能嗎?我錯過了什麼?我認爲答案應該很簡單,但我在NodeJ中是一個新的王者。

+0

是它的可能,但首先讓我們知道你是如何調用'Eventsource'? – 2014-09-26 23:09:58

+0

@RahilWazir我不明白究竟是什麼問題,在代碼中你可以看到當我創建一個新實例時我調用了'EventSource',然後我訂閱了事件onmessage'和' onerror'。 – Gepser 2014-09-28 03:39:53

回答

1

嗯,我一直在尋找解決方案几天,我解決了我的問題。首先,我的代碼是錯誤的(不更新EventSource的文檔),所以我的代碼應該是這樣的:

var url = 'http://api.example.com/resource' 
var es = new EventSource(url); 

es.on('status', function(e) { 
    console.log(e.data); 
    }).on('result', function(e) { 
    console.log(e.data); 
    }).on('error', function() { 
    console.log('ERROR!'); 
    es.close() 
    }); 
}); 

所以,從服務器的異步響應位於e.data對象,例如應該是這樣的:

var url = 'http://api.example.com/resource' 
var es = new EventSource(url); 

es.on('status', function(e) { 
    console.log(e.data); 
    }).on('result', function(e) { 
    var jsonData = JSON.parse(e.data); 
    console.log(e.data, jsonData.url); 
    }).on('error', function() { 
    console.log('ERROR!'); 
    es.close() 
    }); 
}); 

需要注意的是,我們還沒有的有關錯誤的信息,但是那是因爲EventSource的工作的方式。他們不會從服務器發回錯誤,他們只是上升和錯誤字符串。他們有這個they code

if (!res.headers.location) { 
    // Server sent redirect response without Location header. 
    _emit('error', new Event('error')); 
    return; 
} 
相關問題