Search code examples
javascriptnode.jsserver

What's the most efficient way to call a Node.js backend function with JavaScript


I'm an html5 developer with mainly JavaScript experience. I'm starting to learn the backend using Node.js. I don't have a particular example of this question/requirements. I'd like to call a back end function with JavaScript, but I'm not sure how. I already researched events and such for Node.js, but I'm still not sure how to use them.


Solution

  • Communicating with node.js is like communicating with any other server side technology.. you would need to set up some form of api. What kind you need would depend on your use case. This would be a different topic but a hint would be if you need persistent connections go with web sockets and if you just need occasional connections go with rest. Here is an example of calling a node function using a rest api and express.

    var express = require('express'); 
    var app = express();
    
    app.post('/api/foo', foo);
    
    function foo(req, res){
     res.send('hello world');
    };
    
    app.listen(3000);
    

    From the frontend you can post to this REST endpoint like so.

    $.post("/api/foo", function(data) {
      console.log( "Foo function result:", data );
    });