I'm trying to get information about an error when using EventSource in NodeJs, I think you could understand me better with the following example:
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);
};
In the onerror function I would like to get information about the error but the event
is empty or undefined as well as the es
object (well, this object just cames with a pair of curly brackets {}
). I would like to read the response header in case of error, something like:
es.onerror = function(e) {
console.log(e.header.location);
};
Is this possible? What I'm missing? I think the answer should be very easy but I'm a king of new in NodeJs.
Well, I have been looking a solutions for a couple of days and I solved my problem. First of all my code was wrong (the documentation of the EventSource
is not updated), so my code should look like this:
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()
});
});
So, the asynchronous responses from the server are located in the e.data
object, an example should look like this:
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()
});
});
Note that we don't have yet information about the error but that is because the way the EventSource works. They don't send back the error from the server, they just rise and error string. They have this on their code:
if (!res.headers.location) {
// Server sent redirect response without Location header.
_emit('error', new Event('error'));
return;
}