Wednesday, 5 April 2017

How to call a node function from client-side javascript? (HTML)

I have a node app called index.js that runs express. A while ago I decided to merge a website template and my node app together and everything works fine up to here. I am able to load other paths into the node app (index.js) by using the below code.

var express = require('express');
var app = express();
app.use('/assets', express.static(path.join(__dirname, '/assets')));
app.use(express.static(path.join(__dirname, '/')));

Now, I am able to serve different html pages using express, which means my app is able to access the assets folder and the content inside the folder.

Now, the assets folder contains other folders called js, css and... The HTML template is loading all it's javascript codes from the js folder in assets. Note the javascript codes are not written in the HTML file. Here's an example of how a script is triggered in my HTML code:

<script src="../../assets/js/test.js"></script>
<script type="text/javascript">
        $(document).ready(function(){
            test.theFunction();
        });
    </script>

And here's the javascript code in the following directory:

// assets/js/test.js
test = {
  theFunction: function() {
    res.send("finally...");
    console.log("sup?");
  }
}

I am trying to call the following function inside index.js from test.js:

// /index.js
app.get("/hey", function(req, res) {
  res.send("wassaaa!!");
});

So far, I've tried the following code, but it doesn't call the function:

  $.get('/hey').success(function(response) {
    $scope.final = response;
    console.log(response);
  });

I've also tried module.exports in index.js, but when I require it in test.js I get an error saying that I can't require stuff on the client side.

I've also looked at some examples regarding require.js, but the examples mostly explain how to load require.js in the HTML file rather than directly in a js file.

To sum it up, here's what I want to happen: HTML file triggers the functions in test.js, then test.js gets some data from index.js and passes it to the HTML file again... I am trying to avoid writing the javascript codes in the HTML file.

I'm also open to suggestions if anyone knows how to achieve what I am trying to do in an easier way. Thanks in advance...



via bbkrz

No comments:

Post a Comment