Search code examples
javascriptnode.jsglitch-framework

How to call a server-side NodeJS function using client-side JavaScript


I'm working on creating a basic login system, and since the server-side uses NodeJS, but client-side doesn't. I have to make any calls that use NPM packages on the server side. The issue is I have no clue how to call a server-side NodeJS function from the Client-Side JavaScript. Basically I wan't to be able to call a function that's stored on the server from the client browser.


Solution

  • Make a route in your nodejs application like so:

    app.get('/users', function(req, res) {
     // Your function to be called goes here.
    });
    

    Now you can call this code from your client side javascript using ajax. Like this:

    $.ajax({
     type: 'GET'
     url: 'http://localhost:8000/users',
     success: function(response) { 
      console.log(response);
     },
     error: function(xhr, status, err) {
       console.log(xhr.responseText);
     }
    });