I am trying to write a simple node.js based application which can use JustGage (JavaScript-based plugin). Following is my Node.js application.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
Following is the index.html page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Temperature Sensor</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="static/resources/js/justgage.js"></script>
<script type="text/javascript" src="static/resources/js/raphael-2.1.4.min.js"></script>
<script>
window.onload = function(){
var g = new JustGage({
id: "g_a411_faculty",
value: 22,
min: 10,
max: 40,
title: "A411 - Faculty Office",
label: "Celsius",
levelColors: [
"#ffffff",
"#f9c802",
"#FF0000"
]
});
};
</script>
</head>
<body>
<div id="g_a411_faculty" class="col-sm-6" style="width:400px; height:320px"></div>
</body>
</html>
When I run the code and open http://localhost:8080 in Google Chrome, the index page shows an error that JustGage is not defined (in Developer tools). However, when I simply open up index.html (without using Node.js) in Chrome, the page works fine. Can you please help where am I going wrong?
I tried to resolve the issue by installing justgage package by
npm install justgage
However, when I write
var jg = require('justgage');
This shows a Reference Error - the document is not defined. Please help!
node.js isn't serving your static folder.
The website works when running directly from the folder as you are able to access the relative path of static/...
from the same location.
When you run via node.js, you are only serving index.html and not the related assets.
Some useful ways of serving static files/folders are discussed in this thread
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.