I am using Node.JS with Express. The following line fails, and I need help fixing it.
var routines = require("myJsRoutines.js");
When I run index.html and click MenuItem
, I get the first alert, but not the second one.
I have both files in the same directory. Thanks
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="javascript:myMenuFunc('Level 1');">MenuItem</a>
<script>function myMenuFunc(level) {
alert("myMenuFunc1:" + level);
var routines = require("myJsRoutines.js");
alert("myMenuFunc:2" + level);
routines.processClick(level);
alert("myMenuFunc:3" + level);
}</script>
</body>
</html>
myJsRoutines.js:
exports.processClick = function processClick (param1) {
console.log(param1)
}
I am using Node.JS with Express. The following line fails, and I need help fixing it.
var routines = require("myJsRoutines.js");
When I run index.html and click MenuItem
, I get the first alert, but not the second one.
I have both files in the same directory. Thanks
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="javascript:myMenuFunc('Level 1');">MenuItem</a>
<script>function myMenuFunc(level) {
alert("myMenuFunc1:" + level);
var routines = require("myJsRoutines.js");
alert("myMenuFunc:2" + level);
routines.processClick(level);
alert("myMenuFunc:3" + level);
}</script>
</body>
</html>
myJsRoutines.js:
exports.processClick = function processClick (param1) {
console.log(param1)
}
Share
Improve this question
edited Aug 29, 2016 at 21:03
baao
73.4k18 gold badges150 silver badges207 bronze badges
asked Aug 29, 2016 at 21:01
P.NuzumP.Nuzum
1291 gold badge4 silver badges10 bronze badges
2
- i think you are running this via browser. And this is the user-side javascript. you should use ajax to call server-side code. – ArtemSky Commented Aug 29, 2016 at 21:05
- Yes, I am running this on Chrome localhost, to test things out in Node.JS. I’ve never used Ajax, and don’t know how that will solve my problem. – P.Nuzum Commented Aug 29, 2016 at 21:29
3 Answers
Reset to default 1Script in <script>
tags only runs on the client, and script on the server never directly handles DOM events like clicks. There is no magical event wireup - you need to make them interact.
Assuming folder structure from http://expressjs./en/starter/generator.html
Updated module code, in /modules/myJsRoutines.js
...
var myJsRoutines = (function () {
var multiplier = 2;
return {
processLevel: function (level, callback) {
console.log('processLevel:', level); // CLI or /logs/express_output.log
// validation
if (!level) {
// error is usually first param in node callback; null for success
callback('level is missing or 0');
return; // bail out
}
// processing
var result = level * multiplier;
// could return result, but need callback if code reads from file/db
callback(null, result);
}
};
}()); // function executed so myJsRoutines is an object
module.exports = myJsRoutines;
In /app.js
, load your module and add a get
method...
var myJsRoutines = require('./modules/myJsRoutines');
app.get('/test', function (req, res) {
var level = parseInt(req.query.level) || 0;
console.log('server level:', level);
myJsRoutines.processLevel(level, function (err, result) {
if (err) {
res.status(500);
return res.send(err);
}
res.send('result ' + (result || '') + ' from the server');
});
});
In /public/index.html
, add client script to make an HTTP request to the get
method...
<a class="test" href="#" data-level="1">Test Level 1</a>
<a class="test" href="#" data-level="2">Test Level 2</a>
<script src="https://code.jquery./jquery-2.2.4.min.js"></script>
<script>
$(function(){ // jQuery DOM ready
$('.test').click(function () { // click event for <a class="test">
var level = $(this).data('level'); // from data-level="N"
var url = '/test?level=' + escape(level);
console.log('client url:', url);
// HTTP GET http://localhost:3000/test?level=
$.get(url, function (data) {
console.log('client data:', data); // browser console
});
return false; // don't navigate to href="#"
});
});
</script>
...start the server from the mand line...
npm start
...open http://localhost:3000/
in your browser, Ctrl+Shift+i to open the browser console, and click the links.
Run from a node server..var routines = require("myJsRoutines.js"); in the server.js file and Just call a javascript onclick function..and post parameters..for posting parameters..you'll be needing Ajax...and console log the data in node..or After sending the data to the node server..run the function in node server.
Code snippet for calling the function from a href.. and
`<a href="www.blabla." onclick="return myMenuFunc('Level 1');">MenuItem</a>
<script type="text/javascript">
function myMenuFunc('Level 1') {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
`
This line:
var routines = require("myJsRoutines.js");
fails because the require statement is a nodejs function. It does not work with the browser nor does it work with javscript natively. It is defined in nodejs to load modules. To see this
go to your mand line and run this
> node
> typeof require
'function'
go to your browser console; firefox - press Ctrl + K
>> typeof require
"undefined"
To achieve your aim, there are two options that e to my mind
// Assumed Express server running on localhost:80
var express = require('express');
var app = express();
app.get("/myJsRoutines", loadRoutines);
app.listen(80);
Option I: XMLHttpRequest This is a browser API that allows you to open a connection to a server and talk with the server to collect stuff using HTTP. Here's how you do this
<script>
var request = new XMLHttpRequest(); // create an xmlhttp object
request.open("GET", "/myJsRoutines"); // means GET stuff in there
request.link = link;
// wait for the response
request.addEventListener("readystatechange", function() {
// checks if we are ready to read response
if(this.readyState === 4 && this.status === 200) {
// do something with response
}
})
//send request
request.send();
</script>
Lookup XMLHttpRequest API or the new fetch API
Option II: Pug Pug, formerly named jade is a templating engine for nodejs. How does it work? You use it to programmatically create the html on the server before sending it. Lookup the site -> https://pugjs/