I'm looking a way to get an asynchronous request from nodejs (exactly, server side to server side). What is the best way to do it (or at least, one way)?
curl -H "accept:text/event-stream" http://api.example.com/createAccount
Note that the response should be asynchronous and will look like this:
event: status
id: 1
data: {"id":651,"country":{"code":"gt"},"service":{"slug":"something"},"state":"created"}
event: status
id: 2
data: {"id":651,"country":{"code":"gt"},"service":{"slug":"something"},"state_change":{"from":"reserved","to":"querying"}}
event: status
id: 3
data: {"id":651,"country":{"code":"gt"},"service":{"slug":"something"},"run_state_change":{"from":"idle","to":"busy"}}
event: status
id: 4
data: {"id":651,"country":{"code":"gt"},"service":{"slug":"something"},"state_change":{"from":"querying","to":"ready"}}
event: status
id: 5
data: {"id":651,"country":{"code":"gt"},"service":{"slug":"something"},"run_state_change":{"from":"busy","to":"idle"}}
event: result
id: 6
data: {"id":"651","state":"ready","url":"http://accounts.example.com/v1/services/accounts/651"}
... and then we are done, we have our ready
state and the server has stop responding.
I have been trying a while and I couldn't get the expected result, one way I tried was this one:
var EventSource = require('eventsource');
var es = new EventSource('http://api.example.com/createAccount');
es.onmessage = function(e) {
console.log(e.data);
};
es.onerror = function() {
console.log('ERROR!');
};
But the onmessage
method appears not to be working for me.
I tried another ways but always the same result... the request waits until the server has done and then I have my result.
Could you help me with this?