【问题标题】:Best way to do an asynchronous curl in NodeJs在 NodeJs 中进行异步 curl 的最佳方法
【发布时间】:2014-09-30 13:19:18
【问题描述】:

我正在寻找一种从 nodejs 获取异步请求的方法(确切地说,服务器端到服务器端)。最好的方法是什么(或至少是一种方法)?

curl -H "accept:text/event-stream" http://api.example.com/createAccount

请注意,响应应该是异步的,看起来像这样:

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"}

...然后我们就完成了,我们有我们的ready 状态并且服务器已经停止响应。

我已经尝试了一段时间,但我无法得到预期的结果,我尝试的一种方法是:

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!');
};

onmessage 方法似乎对我不起作用。

我尝试了其他方法,但结果始终相同...请求等待服务器完成,然后我得到结果。

你能帮我解决这个问题吗?

【问题讨论】:

  • 您的 EventSource 网址与您在 cURL 中使用的网址不匹配。

标签: javascript node.js http asynchronous request


【解决方案1】:

问题在于您的事件已命名,因此默认事件消息处理程序不会捕获它们(在浏览器实现中也会发生同样的情况,除非您使用浏览器的addEventListener() API 来侦听事件)。试试这个:

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!');
});

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多