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

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.




I'd suggest use Socket.IO

Server-side code

var io = require('').listen(80); // initiate 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) {  

and client-side

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

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

And fire AJAX request using JQuery

    type: 'get',
    url: '/somepath',
    success: function (data) {
        // use data

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

"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: ''})

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

const result = await api.yourApiMethod()

Try it out. Hope it helps.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.