2017-01-09 60 views
0

我試圖發送一個GET請求到API usign Socket.IO在Socket.IO

//socket 
var app = require('http').createServer(handler) 
var io = require('socket.io')(app); 
var fs = require('fs'); 
var apiPath='localhost:1242/api/v1/'; 

app.listen(8090); 


io.on('connection', function (socket) { 
    socket.on('getBanners', function(data){ 
    socket.get(apiPath+'1/1/1', function (resData) { 
     console.log(resData) 
     socket.emit('response', {data:resData}) 
    }) 
    }); 
}); 

我的觀點

<script type="text/javascript"> 
     $(document).ready(function(){ 
      var socket = io('http://localhost:8090'); 
      socket.on('response',function(data){ 
       alert(data) 
      }); 
     }); 
    </script> 

的想法是保持的情況下刷新數據獲取請求api信息已更改。 但我不知道怎麼就SocketIo側的GET請求

回答

0

我發現了一個解決方案 在我的插座我以前要求模塊

var app = require('http').createServer(handler) 
var io = require('socket.io')(app); 
var fs = require('fs'); 
var apiPath='http://localhost:1242/api/v1/'; 
var request = require('request'); 

app.listen(8090); 


io.on('connection', function (socket) { 
    socket.on('getBanners', function(data){ 
    request.get(apiPath+'1/1/1',function (error, response, body){ 
     socket.emit('result', {res:JSON.parse(body)}) 
    }) 
    }); 
});