做在一个的NodeJS异步卷曲的最佳方法 [英] Best way to do an asynchronous curl in NodeJs
问题描述
我正在寻找一种方式来获得的NodeJS(确切地,服务器端服务器端)的异步请求。什么是这样做(或至少,单程)的最好方法?
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!');
};
但的onMessage
的方法似乎并不为我工作。
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.
你能不能帮我?
推荐答案
的问题是,您的活动命名,因此它们不会被默认的事件消息处理程序捕获(同样的情况在浏览器中实现,除了有使用浏览器的的addEventListener()
API侦听事件)。试试这个:
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!');
});
这篇关于做在一个的NodeJS异步卷曲的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!