CJH
CJH

Reputation: 187

node.js index.html javascript function not defined

I have an 'index.html' page that references a javascript file of mine, 'bargraph1.js', that is in the same directory as index.html. In the html file, I call a function in that js page:

<!DOCTYPE html>
<html lang="en">
   <head>
     <meta charset="utf-8">
     <title>D3 Test</title>

     <script type="text/javascript" src="d3.v4/d3.js"></script>
     <script type="text/javascript" src="bargraph1.js"></script>

  </head>
  <body>
    <h2>BarGraph</h2>
      <script type="text/javascript">
         barGraph(null, null, null, 30);
      </script>

  </body>
</html> 

The file bargraph1.js contains one function 'barGraph()' that uses d3 to render a bar graph.

If I open this file with 'file open' in my browser, it renders beautifully with no errors in the browser error console.

HOWEVER, if I try to serve the page from a nodejs server, the bar graph does not appear and the console shows 'barGraph not defined'. The h2 header preceeding it does show up, though. (Actually I don't think it can find anything in any of the referenced .js files when served by the server). Here's the server code:

var app  = require ('express')();
var http = require ('http').Server(app);
var io   = require ('socket.io')(http);

var pagePath = __dirname + '/index.html';
console.log('sending page ' + pagePath + '\'');
app.get ('/', function(req, res) { res.sendFile(pagePath); });

io.on ('connection', function(socket) {
   console.log ('\nsocket.id ' + socket.id + ' connected');

   socket.on ('disconnect', function() {
      console.log ('\nsocket.id ' + socket.id + ' disconnected');
   });
});

//===================================================
// set HTTP server to listen on port 3001
//===================================================

http.listen (3001, function() {
    console.log(' (3) http listening on *:3001 '); 
});

SO - obviously there is something different about how things get resolved (paths?) in these two different ways to show the html page with javascript. I have been using this same bargraph1.js file many times in files opened locally in the browser so I am sure there are no syntax errors in it.

How can I get this file and the functions contained in it to work with a nodejs server?

Thanks

Upvotes: 0

Views: 1531

Answers (1)

CoconutFred
CoconutFred

Reputation: 454

You need to create routes for the URLs inside the <script> tags. Otherwise, when your browser requests those script files, it will get a 404 from the Node server (this doesn't happen when you just double-click the HTML file because your computer automatically serves those files using directories as URL paths). Since you're using Express now, try running

app.use(express.static(path.resolve(__dirname, '/')));

and then at the end instead of doing http.listen, run

app.listen(3001, process.env.IP || "0.0.0.0", function() {
    console.log(' (3) http listening on *:3001 '); 
});

Upvotes: 1

Related Questions