2

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.

Ethan Mitchell
  • 602
  • 5
  • 15

4 Answers4

4

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);
 }
});
  • I see, can I put multiple functions inside the app.get, or do I need to change the '/users' for each function? – Ethan Mitchell Dec 22 '18 at 16:21
  • You can pass any number of callbacks to the routes like app.get('/users', cb1, cb2, ...). [This](https://stackoverflow.com/a/26894101/6412356) answer has given a good clarification. – Sankalpa Timilsina Dec 22 '18 at 16:36
0

Create a REST API and map the request parameters to the specific function calls you need to use. See this tutorial on creating REST APIs.

Gordon
  • 170
  • 3
  • 18
0

You do this by calling APIs on the server (a specific url that will to some specific work).In JS you need ajax. Have a look here

//url be the api like '/api/something/'
$("button").click(function(){
  $.ajax({url: "demo_test.txt", success: function(result){
    // your response
  }});
});

in Node we have axios that will do the same example

axios.post('api/tobackend/function',{user:'a',password:'b'})
     .then((res)=>console.log('response from server'))

in backed you might need route to handle the request.

router.post('api/tobackend/function',(reqs,resp)=>{console.log('backend')})
Rajan Lagah
  • 2,373
  • 1
  • 24
  • 40
0
  1. With Socket.io

  2. in JS

    let xhr = new XMLHttpRequest(); xhr.open('GET', '/user/sessionDestroy'); xhr.send();

In Node.JS

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107
Wiki HSK
  • 19
  • 1
  • 1