2017-03-09 72 views
-1

我試圖從網頁獲取數據,但我找不到解決方案。這裏是socket服務器端代碼:Socket.io類似ajax

function get_page(url) { 
 
    //function which return web page data 
 
} 
 
io.sockets.on('connection', function(socket) { 
 
    result=get_page('http://example.com'); 
 
    io.sockets.emit('data',result); 
 
});

+1

這是什麼意思:「套接字服務器之前EMIT數據應該檢查另一頁上的」?請用更多的文字(也可能是一些代碼)解釋你要做的事情。 – jfriend00

+0

我試圖做這樣的事情: 'io.sockets.on('connection',function(socket){ \t $ .ajax({url:「http://example.com」,success:function (結果){ io.sockets.emit('data',result); }}); });' – Mbae

+0

請修改您的問題以在問題本身中添加適當的代碼和說明。在棧溢出時,你有責任寫出一個好問題,如果你不這樣做,社區將會刪除它(帶有downvotes和closevotes)。另外,發佈一個問題並且僅在18個小時之後纔回來就不合適。這是一個無法實現的實時站點,不像您在第二天發佈並回來的BBS。請從這裏的幫助中心閱讀[我如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)。 – jfriend00

回答

0

如果你只是問如何實現get_page(),您可以使用http.get()還是有點更容易使用request module。使用request模塊,你的代碼的NodeJS可能是這樣的:

let request = require('request'); 

io.sockets.on('connection', function(socket) { 
    // upon initial connection, fetch some data and send it to the connecting client 
    request('http://example.com', function(err, response, body) { 
     if (err) { 
      // send some error response here 
      socket.emit('data', "example.com not responding - no data available"); 
     } else { 
      // send data to the connecting socket 
      socket.emit('data', body); 
     } 
    }); 
}); 
+0

謝謝!它工作 – Mbae