17

I'm new to node.js but I know somewhat about socketstream web framework by using this I can easily call a server side node.js method from JavaScript. I don't know how to do this without using that framework. How can I call the node.js method from JavaScript?

The below code is using socketstream to call server side method. So I want to call the same server side method without using this framework.

ss.rpc('FileName.methodName',function(res){ 
    alert(res);         
});
3
  • 1
    Afaik (correct me if I'm wrong), you can't directly call a method on the server from a client. You can however, send some sort of request to the server with the method name attached, and then the server can invoke it. Commented Feb 19, 2013 at 6:35
  • @Supericy :thanks for your response but i don't know how to call directly.can u explain that in code. Commented Feb 19, 2013 at 6:38
  • 1
    You need to expose an endpoint for the client to request. With express.js, that might be something like app.get('/some.name', function(req, res) { // call code }). Then you can hit that endpoint via an AJAX call on the client. Commented Feb 19, 2013 at 6:46

2 Answers 2

18

I'd suggest use Socket.IO

Server-side 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 which calls some function on specific request from the 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 fire AJAX request using JQuery

$.ajax({
    type: 'get',
    url: '/somepath',
    success: function (data) {
        // use data
    }
})
Sign up to request clarification or add additional context in comments.

3 Comments

Socket.IO may be overkill if they are not sending a large number of requests (which the OP seemed to indicate).
Agreed, alternatively he can use connect and a router function to call some function when client fires an HTTP request.
I realize that this thread is a bit dated but how about using express? as var app = express();.....app.get('/dbquery',function(req,res){//do some db stuff....}); .....app.listen(2999,function(){...}); this would make a service listening on port 2999 and any call to the /dbquery service would return/do something based on the request.
1

Not exaclty sockets but a simple solution:

Can I suggest trying api-mount. It basically allows calling API as simple functions without having to think about AJAX requests, fetch, express, etc. Basically in server you do:

const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)

"api" is basically an object of methods/functions that you are willing to call from your web application.

On the web application you then do this:

const api = mountApi({baseUrl: 'http://your-server.com:3000'})

Having done that you can call your API simply like this:

const result = await api.yourApiMethod()

Try it out. Hope it helps.

5 Comments

Really good solution, I wonder why nobody upvoted this answer as socket.io is definitely a overkill!
Feel free to use. I think I will need to improve documentation or make some YouTube with explanation to attract more users. It is super easy to use but I realize that docs look over-complicated :D
Yes, that would we awesome as well. BTW: I created my own solution becoz I didn't read your answer at that time. Check it out at: npmjs.com/package/rpc-middleware Demo here: rpc-demo.herokuapp.com
Cool! Simple lightweight solution and tbh very similar. Abstraction is maybe at a slightly different level. api-mount abstracts away both client and server. There is one entry-point for browser and another for server even though it is only 1 package. Or alternatively someone could use api-mount-client or api-mount-server if they do not like having 2 in 1.
Yes, I am fan of your approach and library. A good thing I implemented with my lib is that I added support for integrating it with any existing express servers. And that makes it usable by existing backend servers using expressjs. To be honest I haven't used either of lib in any project yet but it is way too cool though. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.