Reputation: 359
I am working on a software project with a team, and I would like to add a page that displays a bar chart using Chart.js. The project is using Node.js, and we are using Express.js to render the views on our server.
The issue is that when I displayed the page with the bar chart on its own, it worked just fine. When I tried to run the server (i.e. node app.js), however, the page wouldn't display the chart, no matter where I placed my JavaScript code for drawing the chart.
Here is my EJS file with the chart:
<!DOCTYPE html>
<head>
<title>Connect Concordia</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<!-- load bootsrap css -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<script type="text/javascript" src="../node_modules/chart.js/dist/Chart.js"></script>
</head>
<body>
<canvas id="myCanvas" width="400" height="400">Your browser does not support the canvas feature.</canvas>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Strongly Agree', 'Agree', 'Neither Agree nor Disagree', 'Disagree', 'Strongly Disagree'],
datasets: [{
label: 'Number of Responses',
data: [5, 10, 6, 3, 2],
backgroundColor: "rgb(100, 100, 100)"
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
min: 0,
max: 50,
stepSize: 10
}
}]
}
}
});
</script>
</body>
</html>
And this is the code to render the page on the app, found in a larger file called routes.js:
res.render('sp-results.ejs')
Note: I myself am new to Node.js, so if there is anything else I need to know please inform me. Any help on this issue would be appreciated.
UPDATE:
Upon inspecting the page using Chrome, I found this error message: Failed to load resource: the server responded with a status of 404 (Not Found)
From that, I found out that the reason why the chart isn't displaying is because the server can't reference the library. Since Chart.js isn't a Node.js library, how can I 'require' the Chart.js library?
Upvotes: 2
Views: 5939
Reputation: 10705
One thing you could try is not initializing your chart until the document is for sure ready. You can do this using window.onload
.
window.onload = function() {
// put chart.js code here
}
Also, I notice that you are trying to link to a chart.js build located in your node_modules
folder. I'm not exactly sure how to do this in express in an ejs file, but take a look at this answered question for an example on how to handle this.
You can always use the script hosted on a cdnjs to quickly validate your page is working. Here is an example.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
Upvotes: 5