在NodeJ中执行异步卷曲的最佳方式

Best way to do an asynchronous curl in NodeJs

本文关键字:最佳 方式 异步 NodeJ 执行      更新时间:2023-09-26

我正在寻找一种从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方法似乎对我不起作用

我尝试了另一种方法,但结果总是一样请求等待,直到服务器完成,然后我得到结果

你能帮我做这个吗?

问题在于,您的事件是命名的,因此它们不会被默认的事件消息处理程序捕获(在浏览器实现中也会发生同样的情况,只是您使用浏览器的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!');
});