2013-02-19 27 views
8

Sono nuovo su node.js ma conosco piuttosto il framework Web di socketstream utilizzando questo metodo, posso facilmente chiamare un metodo node.js lato server da JavaScript. Non so come farlo senza usare quella struttura. Come posso chiamare il metodo node.js da JavaScript?Come chiamare il metodo lato server node.js da javascript?

Il codice seguente utilizza socketstream per chiamare il metodo lato server. Quindi voglio chiamare lo stesso metodo lato server senza usare questo framework.

ss.rpc('FileName.methodName',function(res){ 
    alert(res);   
}); 
+1

AFAIK (correggetemi se sbaglio), non è possibile chiamare direttamente un metodo sul server da un client. Tuttavia, è possibile inviare una sorta di richiesta al server con il nome del metodo collegato, quindi il server può richiamarla. – Supericy

+0

@Supericy: grazie per la tua risposta, ma non so come chiamare direttamente.puoi spiegarlo nel codice. – user1629448

+1

È necessario esporre un endpoint per il client da richiedere. Con express.js, potrebbe essere qualcosa come 'app.get ('/ some.name', function (req, res) {// call code})'. Quindi puoi colpire quell'endpoint tramite una chiamata AJAX sul client. – jli

risposta

10

Io suggerirei uso Socket.IO

codice lato server

var io = require('socket.io').listen(80); // initiate socket.io server 

io.sockets.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); // Send data to client 

    // wait for the event raised by the client 
    socket.on('my other event', function (data) { 
    console.log(data); 
    }); 
}); 

e lato client

<script src="/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect('http://localhost'); // connec to server 
    socket.on('news', function (data) { // listen to news event raised by the server 
    console.log(data); 
    socket.emit('my other event', { my: 'data' }); // raise an event on the server 
    }); 
</script> 

In alternativa, è possibile utilizzare una funzione di router, che chiama alcune funzioni su specifiche r equest dal client

var server = connect() 
    .use(function (req, res, next) { 
     var query; 
     var url_parts = url.parse(req.url, true); 
     query = url_parts.query; 

     if (req.method == 'GET') { 
     switch (url_parts.pathname) { 
      case '/somepath': 
      // do something 
      call_some_fn() 
      res.end(); 
      break; 
      } 
     } 
    }) 
    .listen(8080); 

E il fuoco AJAX richiesta utilizzando JQuery

$.ajax({ 
    type: 'get', 
    url: '/somepath', 
    success: function (data) { 
     // use data 
    } 
}) 
+0

Socket.IO può essere eccessivo se non invia un numero elevato di richieste (che l'OP sembrava indicare). – jli

+0

D'accordo, in alternativa può usare 'connect' e una funzione router per chiamare qualche funzione quando il client attiva una richiesta' HTTP'. –

+0

grazie per tutto. Proverò ad usare socket.IO .. – user1629448

Problemi correlati