1

I am using node.js on Windows, with express module to generate a static page that has a Submit form which I want to run an update() function on the Server (i.e. not expose my js file publicly) when someone clicks "Submit" button.

PROBLEM:

It seems my update() function fails to be recognized from the HTML. The following error is generated:

Uncaught ReferenceError: update is not defined at HTMLInputElement.onclick ((index):23)

I suspect this is the result of my node project not being set up correctly.


Server file (server.js):

var fs = require('fs');
var express = require("express");
var app     = express();

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

//loading all files in public folder
//see instructions in https://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

app.listen(8080);

console.log("Running at Port 8080");

HTML file (index.html):

<!DOCTYPE html>
<html>

<body>

<div id="div1">
  <p id="p1">This is a static paragraph.</p>
</div>

<p>
  <script type="text/javascript" src="start.js"></script>
</p>

Input:
<br>
<input type="text" name="human_input" value="">
<br>
<input type="button" value="Submit" onclick="update()">

</body>
</html>

JS file (compute.js)

function update() {
    console.log("this is running!")
}

^^ note, this is a sample script I am trying to get working.

My folder structure

/
- node_modules
-- *
- public
-- start.js
- index.html
- compute.js
- package-lock.json
- server.js
- start.js

Notes:

  • calling update() from onclick worked previously when I was not using node.
Wronski
  • 1,506
  • 3
  • 18
  • 37
  • 1
    Node runs on the server side. What you are looking to do is client side execution. – Pavan Andhukuri Oct 06 '18 at 07:58
  • 1
    Maybe you should require the `compute.js` file in your `index.html`? It seems you only require `start.js`? However if you wan't the node server side to communicate you are going to need a transport such as http, web sockets or something similar. – nijm Oct 06 '18 at 07:58
  • @PavanAndhukuri, that makes sense. I am happy to refactor my code for server side execution. What would be the first step? Or is there a link to documentation you could provide? – Wronski Oct 06 '18 at 08:00
  • @nijm you were correct, that got the code working on the client side. I have edited this post for some help on moving the code from client to server side. But happy to go through documentation if you have any. – Wronski Oct 06 '18 at 08:06

1 Answers1

2

You miss script tag in html file pointing on compute.js file, that is why your update doesn't work.

Just duplicate your script you already have in html file and change src attribute to compute.js value

lkrocek
  • 50
  • 4