How to call server.node.js method from javascript?

I am new to node.js, but I know a little about socketstream web infrastructure, using this, I can easily call the server.nodes node.js method from JavaScript. I do not know how to do this without using this structure. How can I call the node.js method from JavaScript?

The code below uses the socketstream method to invoke the server-side method. Therefore, I want to call the same method on the server side without using this infrastructure.

ss.rpc('FileName.methodName',function(res){ alert(res); }); 
+8
javascript
source share
1 answer

I would suggest using Socket.IO

Server code

 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); }); }); 

and client side

 <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> 

Alternatively, you can use a router function that calls some function on a specific request from a 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); 

And a fire AJAX request using jQuery

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

All Articles