2014-09-30 31 views
0

我正在尋找一種方法來從nodejs(確切地說,服務器端到服務器端)獲取異步請求。做到這一點的最佳方式是什麼(或者至少有一種方法)?在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方法似乎並不爲我工作。

我試過另一種方式,但總是相同的結果... 請求等到服務器完成,然後我得到了我的結果。

你能幫我解決嗎?

+0

你的'EventSource'網址與你在cURL中使用的不匹配。 – mscdex 2014-09-30 01:24:46

回答

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

太棒了,你的解決方案的作品! – Gepser 2014-09-30 14:46:26