0

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?

1
  • Your EventSource url doesn't match what you were using in cURL. Commented Sep 30, 2014 at 1:24

1 Answer 1

1

The problem is that your events are named, so they are not captured by the default event message handler (the same happens in the browser implementations, except there you use the browser's addEventListener() API to listen for events). Try this instead:

var es = new EventSource('http://api.example.com/createAccount');
es.on('status', function(e) {
  // status event
  console.log(e.data);
}).on('result', function(e) {
  // result event
  console.log(e.data);
}).on('error', function() {
  console.log('ERROR!');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.