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

I have a node app called index.js

express that works. A while ago I decided to merge the site template and my node app and everything works fine. I can load other paths into node ( index.js

) app 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 can serve different html pages using express, which means my application can access the folder assets

and the contents inside the folder.

The assets folder now contains other folders called js, css and ... The HTML template loads all of its javascript codes from the folder js

into assets

. Please note that the javascript codes are not written in the HTML file. Here's an example of how the script runs in my HTML:

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

      

And here is 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 internally 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 also tried module.exports

in index.js

, but when I need it in test.js

, I get an error saying that I cannot claim anything on the client side.

I've also looked at some examples regarding require.js, but the examples mainly explain how to load require.js into an HTML file, not directly into a js file.

To summarize, here's what I need: the HTML file runs the functions in test.js

, then test.js

gets some data from, index.js

and feeds it back to the HTML file again ... I'm trying to avoid writing javascript codes in the HTML file.

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

+3


source to share


2 answers


You have to write the function in test.js

and import it in index.js

. For example, a function getResponse()

that returns "wassaaa !!" in test.js and in index.js useres.send(test.getResponse())



0


source


For this you need to use a URL. Below is an example of your dev environment, assuming your application is listening on port 8800:



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

      

0


source







All Articles