Best way to do an asynchronous curl in NodeJs

2019-09-09 21:55发布

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条回答
倾城 Initia
2楼-- · 2019-09-09 22:36

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!');
});
查看更多
登录 后发表回答